Jim Gibson <jimsgib...@gmail.com> writes: > On Jun 13, 2013, at 10:51 AM, lee wrote: >> + When I create files with lines like "filename:size:mtime" or >> "filename:hash", is there something built in to read a syntax like >> this into, let's say, an array like "my @fileinfo;" with $fileinfo[0] >> being the file name, $fileinfo[1] the hash? >> Such 'key:value:...' combinations is probably something frequently >> used. I'm finding some examples to this and don't know what would be >> the best way to do it. > > > The split function is the normal way of parsing lines like 'filename:hash'. > You have to make sure that your data fields do not contain the ':' character, > or whatever character you use to delimit your fields. > > my @fields = split(':',$line); > > For more complicated formats, the Text::CSV module can be used. > > You could also use the Storable or Data::Dumper modules to write out a hash > or array containing your data structure to a file and read it back the next > time you run your program.
Thank you! So I started implementing some functions (simple and inefficient), and for reading size, mtime and has from a file, I came up with this: [CODE] [...] sub dbreadhash { # # dbreadhash("hashs.list", "filename"): find the entry for "filename" in the # hashs.list and return size, mtime and hash # my ($filename, $key) = @_; $key .= ":"; my @ret; if( -e $filename) { open(my $file, "<$filename"); while( <$file> ) { chomp $_; if( m/^$key/ ) { @ret = split(':', $'); #' last; } } close($file); } else { print $filename . " not found\n"; } if(scalar(@ret) != 3) { print "no or invalid syntax in " . $filename . "\n"; @ret = ( -1, -1, ""); } return @ret; } # test: try out dbreadhash my @test = dbreadhash("testfile", "this"); print $test[0] . "\n"; [/CODE] This is expecting lines like: /path/filename:123:456:hash How is the return value of the split() function defined for instances when splitting is not possible? All the documentation I found uses examples that can be split, and checking the array size like this is merely based on assumptions ... -- "Object-oriented programming languages aren't completely convinced that you should be allowed to do anything with functions." http://www.joelonsoftware.com/items/2006/08/01.html -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/