"James Linden Rose, III" wrote:

> I have a data file whose field order is fluid, but whose names are
> known, and whose records are delimited by returns, and whose fields
> are delimited by tabs.  The data file is stored in say @File.  But
> the first record contains the one word name of the field.  

you didn't say if you only need to process
the data a record at a time or if you need
to accumulate all the records into a master
list. 

i.e. do you need to look at one person's 
address and phone number, or do you need to
create phone book that you can process.

this piece of code should give you a start.
if you dont need a master list, then 
don't do the push inside the while loop.
depending on how big your file is, 
you may not be able to do it.



open(my $fh, $filename);

# get first line with field names.
my $line;
unless(defined($line=<$fh>))
        {
        die "file is empty";
        }

my @fields_by_order = split(/\t/, $line);

# read rest of file, line by line,
# and pull out the data for a single record.

my @master_records;

while(<$fh>)
        {
        my @data_by_order = split(/\t/, $_);

        my %data_by_field;

        # put the data into the hash
        # data will appear in same order as 
        # the order of fields on first line.
        for(my $i=0;$i<scalar(@fields_by_order);$i++)
                {
                $data_by_field{$fields_by_order[$i]} =
                        $data_by_field[$i];
                }

        # hash data_by_field can now access the
        # data for this line by field name.
        # i.e. to get the name of the current record:
        my $name = $data_by_field{Name};

        print "$name\n";

        # push hash ref into global storage
        # if you want (and if you have the memory)
        push(@master_records,\%data_by_field);
        }

close($fh);

# later, if you need to process all the records at once,
# then @master_records is an array of hashes,
# each hash is one record.

foreach my $record (@master_records)
        {
        my $name = $record->{Name};
        print "$name\n";
        }


hope this helps,
Greg

Reply via email to