Very similar approach with nice formatting.
-------------------------------------------
use warnings;
use strict;
my (@day, @fruitname, %totals);
my $x;
open DATA, "data.txt";
@fruitname = split /[,\s]+/ => <DATA>;
while ( <DATA> ) {
my %fruit;
@fruit{ @fruitname } = split /[,\s]+/ => $_ ;
$day[$x++] = \%fruit;
}
foreach my $day ( 0 .. $#day ) {
print "Day: ", $day+1, "\n";
foreach my $fruit( sort keys %{ $day[$day] } ) {
print "\t$fruit\t";
print "\t" if length($fruit)<9;
print "$day[$day]->{$fruit}\n";
$totals{$fruit} += $day[$day]->{$fruit};
}
}
print "Totals:\n";
foreach my $fruit ( sort keys %totals ) {
print "\t$fruit\t";
print "\t" if length($fruit)<9;
print "$totals{$fruit}\n";
}
-----Original Message-----
From: David Gray [mailto:[EMAIL PROTECTED]]
Sent: Friday, April 12, 2002 9:34 AM
To: [EMAIL PROTECTED]; [EMAIL PROTECTED]
Subject: RE: splitting / regex / trend etc
> If I only want to get the numbers sold for lets say apples,
> oranges and
> grapefruit, for both stores How would I go about it?
>
> <File for Store A>
> apples, oranges, pears, lemons, grapefruit
> 5, 0, 4, 6, 2
> 2, 6, 2, 0, 0
> 4, 7, 2, 1, 0
>
> <File for Store B>
> apples, melon, oranges, pears, coconut, lemons, grapefruit
> 4, 3, 2, 7, 1, 4, 0
> 3, 1, 4, 4, 0, 0, 1
> 0, 4, 0, 0, 4, 5, 0
open F,'</path/to/your/file.txt';
chomp(my $fruits = <F>);
my @fruits = split /,\s*/,$fruits;
my $count = 0;
while(<F>) {
chomp;
my @currvals = split /,\s*/;
for(0..scalar @fruits - 1) {
$dayvals[$count++]->{$fruits[$_]} = $currvals[$_];
}
}
close F;
Then for day x, you can access the fruit totals like so:
$dayvals[1]->{melon}
The above code builds an array of hashes, one for each line (day). I
suppose if you're after totals, you could use a hash instead, like so
(re-using the above code where not specified):
my %totals = ();
while(<F>) {
chomp;
my @currvals = split /,\s*/;
for(0..scalar @fruits - 1) {
$totals{$fruits[$_]} += $currvals[$_];
}
}
So now you can access the totals for each file by:
$totals{melon}
HTH,
-dave
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]