Perlseeker_1 has asked for the wisdom of the Perl Monks concerning the following question:
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: Perl - write data from hashes
by aitap (Curate) on Oct 13, 2013 at 15:24 UTC | |
by Happy-the-monk (Canon) on Oct 13, 2013 at 15:34 UTC | |
|
Re: Perl - write data from hashes
by CountZero (Bishop) on Oct 13, 2013 at 17:25 UTC | |
by marinersk (Priest) on Oct 14, 2013 at 05:51 UTC | |
|
Re: Perl - write data from hashes
by Lennotoecom (Pilgrim) on Oct 13, 2013 at 20:19 UTC |