This code is basically the same as yours, but It creates only one variable to encapsulate the data. For my data stucture I chose to implement a hash of arrays to easily preserver the file order, but you could implement a hash or hashes unsing the first row as the second hash keys. The downside of this approach is that the code becomes a tad more verbose, but for me the verbosity adds clarity, which is far more valueable in my opinion.use strict; use Data::Dumper; my $data = OpenFlatFile("flatfile.txt", "\t"); my @PEOPLE = @{$data->{'PEOPLE'}}; my @CAR_COLORS = @{$data->{'CAR_COLORS'}}; my @CARS = @{$data->{'CARS'}}; my @AGES = @{$data->{'AGES'}}; for(my $i=0; $i < $data->{'ROWCOUNT'}; $i++) { print "$PEOPLE[$i] drives a $CAR_COLORS[$i] $CARS[$i] "; print "and is $AGES[$i] years old.\n" } print Data::Dumper->Dump([$data]), "\n"; sub OpenFlatFile { my ($datafile, $delimeter) = @_; open(FILE,$datafile) or return {}; chomp (my @tmp = <FILE>); close FILE; my @headers = split /\Q$delimeter\E/, shift @tmp; my $data = {}; $data->{'HEADERS'} = [@headers]; $data->{'ROWCOUNT'} = scalar(@tmp); $data->{'COLCOUNT'} = scalar(@headers); foreach my $line (@tmp) { my @a = split /\Q$delimeter\E/o, $line; push @{$$data{$_}}, shift @a foreach (@headers); } return $data; }
$VAR1 = { 'AGES' => [ 26, 25, 50 ], 'CARS' => [ 'Volks', 'Fiat (yuck)', 'Twingo' ], 'ROWCOUNT' => 3, 'HEADERS' => [ 'PEOPLE', 'CARS', 'CAR_COLORS', 'AGES' ], 'PEOPLE' => [ 'John', 'Mira', 'Mom' ], 'CAR_COLORS' => [ 'avocado', 'black', 'cherry' ], 'COLCOUNT' => 4 };
In reply to RE: Open Flat File
by perlmonkey
in thread Open Flat File
by BBQ
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |