[DGD] Make an array from read_file

Michael McKiel crashnbrn71 at yahoo.ca
Sat Mar 27 01:35:47 CET 2004


I'm trying to create an array, from data from a read_file() and it seems
This is what I came up with, has anyone done/suggest something better? :)

given that the file /home/zamadhi/blah:
    blah ({ "foo", "bar" })

and that we do:
    str = read_file("/home/zamadhi/blah");
    sscanf(str, "%s\n", str);
    arr = get_array_from_string(str);

note: str becomes == "blah ({ \"foo\", \"bar\" })\n"
and:  normally we'd explode the string on "\n" and iterate through 
      the array, instead of the initial sscanf.

mixed * get_array_from_string(string str)
{
    string  tmp;
    mixed  *arr;
    int     i;
    
    if (sscanf(str, "%s %s", str, tmp) != 2) return nil;
    
      /* remove leading/trailing spaces from the string */
	tmp = trim_whitespace(tmp);
	
	if ( sscanf(tmp, "({%s", tmp) == 1 
		&& sscanf(tmp, "%s})", tmp) == 1) {
    
        arr = explode(tmp, "\"");
    
        for (i=sizeof(arr); --i >= 0; )
        {
		    arr[i] = trim_whitespace(arr[i]);
		    if (arr[i] == "" || arr[i] == ",")
                arr[i] = nil;
        }
        arr -= ({ nil });
    
        return arr;
    }
    return nil;
}    

course this breaks down if its an array of arrays, but I think that 
could be handled with another pre-step that checks if it 'looks' 
like an array of arrays and recursively call the function for each
sub-array then create a 2D/3D/etc array from all the returned values.

This also assumes that the array contains strings, it gets a bit too
complex for other types, and easy enough to store int's/float's in a
prospective array as "1" or "1.0" and typecast later if needed.


______________________________________________________________________ 
Post your free ad now! http://personals.yahoo.ca
_________________________________________________________________
List config page:  http://list.imaginary.com/mailman/listinfo/dgd



More information about the DGD mailing list