in reply to Re: Perl - Hashes
in thread Perl - Hashes
Hi Experts,
Thanks for the quick reply
I need help on perl hashes.i have used hashes to store the data. i have fetched data from four files and stored data in hashes.
key and value pair, code written to fetch data and store in hashes
I have created four sub routines for file 1,file 2, file 3 and file 4, the key which i formed for each file will vary
for file 1 --> $key = f[0].f1,file 2 --> f1.f2,file 3 --> $key = f4.f6,file 4 --> $key = f3.f4
code for file 1
my (%r1,%r2,%r3,%r4); my $Total; foreach my $file (@files) { open FILE, "<$dir/$file" or warn "Couldn't open file ($!) or file ($!) + not found\n"; while (chomp ( my @fields = split /\t/, <FILE>) ) { my $key = "$f[0].$f[1]"; if ($c{$key}) { $key = $c{$key}; if (exists($r1{$key})){ $r1{$key} += $f[02]; } else { $r1{$key} += $f[02]; } $Total +=$r1{$key}; } } $r1{'Total'} = $Total; } close FILE;
Example input file 1
A B 12.00 C D 13.00 E F 11.00 G H 22.00
code for file 2
foreach my $file (@files) { open FILE, "<$dir/$file" or warn "Couldn't open file ($!) or file ($!) + not found\n"; while (chomp ( my @fields = split /\t/, <FILE>) ) { my $key = "$f[1].$f[2]"; $key{'Output - Final'}=1; if ($c{$key}) { $key = $c{$key}; if (exists($r1{$key})){ $r1{$key} += $f[03]; } else { $r1{$key} += $f[03]; } $Total +=$r1{$key}; } } $r1{'Total'} = $Total; } close FILE;
Example input file 2
1 A B 12.00 2 C D 13.00 3 E F 11.00 4 G H 22.00
Output got
r1 --> hash contains data as ... Key Value Name F1.A AB 12.00 CD 13.00 EF 11.00 GH 22.00 r2 --> hash contains data as ... Key Value Name F2.B AB 01.00 CD 04.00 EF 42.00 GH 34.00 r3 --> hash contains data as ... Key Value Name F3.C AB 02.00 CD 03.00 EF 15.00 GH 20.00 r4 --> hash contains data as ... Key Value Name F4.D AB 62.00 CD 43.00 EF 24.00 GH 26.00
Output expected
Output - Final Name F1.A F2.B F3.C F4.D AB 12.00 01.00 02.00 62.00 CD 13.00 04.00 03.00 43.00 EF 11.00 42.00 15.00 24.00 GH 22.00 34.00 20.00 26.00 Total 58.00 81.00 40.00 155.00
Thanks
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: Perl - Hashes
by remiah (Hermit) on Oct 14, 2013 at 08:33 UTC |
In Section
Seekers of Perl Wisdom