in reply to Re: Database question: pulling a particular field from a flat database
in thread Database question: pulling a particular field from a flat database

Maintainability notes:
  1. Include the name of the file in the error message. Just knowing that you failed because , "No such file or directory" is not nearly as useful as knowing which file purportedly does not exist.
  2. Why put the lines into an array? It is just as easy to read from the file directly, and that gives you the option of reading it incrementally with a while loop. (Huge improvement on large files.)
  3. Indentation?
  4. You forgot to chomp the lines from the file.
  5. I find that using a hash slice rather than a list of variables is much more maintainable. That way minor (or major) data format changes are much easier to handle.
With those changes this example would become something like:
#! perl use strict; my $file = shift(@ARGV) || "foo.txt"; open(FH, $file) or die("Cannot read '$file': $!"); my @field_list = qw(put in reasonable names here for your data); while (<FH>) { chomp; my %row; @row{@field_list} = split /\|/, $_; my ($field_data, $comment) = split /;/, $row{data}; print "$field_data\n"; }
Of course the original author should switch to a data format which is self-documenting (for instance make the first line a header line that says what fields are in use). And when you do that, the use of a hash slice makes things very easy - just read the list of field names out of the header line!
  • Comment on Re (tilly) 2: Database question: pulling a particular field from a flat database
  • Download Code

Replies are listed 'Best First'.
Re: Re (tilly) 2: Database question: pulling a particular field from a flat database
by foogod (Friar) on Sep 08, 2001 at 00:37 UTC

    Everything you said above is right on the money. The hash slice approach is much "smarter" ... sometimes I have to dumb down things for my coworkers ... and then it gets hard for me to use both halves of the old brain.

    Thanks for the reply ... I will be sure to take a breath before I start spouting off code next time.

    thanks,

    - f o o g o d