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

why not something like this:

#!perl use strict; my $file = "foo.txt"; open (FH, "$file") || die ("unable to open the file!: $!"); my @ODB = <FH>; close (FH); my $line; foreach $line (@ODB) { my ($field1,$field2,$field3,$field4,$field5,$field6,$field7,$field8)=s +plit('\|',$line); my ($field_data,$comment)=split(";",$field8); print "$field_data\n"; }
this is assuming a data file like:
field1data|field2data|field3data|field4data|field5data|field6data|fiel +d7data|field8data1; comment goes here!

HTH

- f o o g o d --- ruining the bell curve for everyone else ---

Replies are listed 'Best First'.
Re (tilly) 2: Database question: pulling a particular field from a flat database
by tilly (Archbishop) on Sep 07, 2001 at 18:06 UTC
    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!

      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