Hello Perlseeker_1
How about using dispatch table? Sometimes I see monks use it.
use strict; use warnings; use Data::Dumper; sub kv1{ my @flds=split(/\s+/, $_[0]); return( $flds[2], $flds[3] ); } sub kv2{ my @flds=split(/\s+/, $_[0]); return( $flds[1] . $flds[2], $flds[3] ); } my ($line,$fname, %data,%all, %kv_func); %kv_func=( #dispatch table 'file 1' => \&kv1, 'file 2' => \&kv1, 'file 3' => \&kv1, 'file 4' => \&kv1, 'file 5' => \&kv2, ); while( <DATA> ){ if (my $num = /^file/ .. /^\n/ ){ # test them with flip-flop chomp($line=$_); if( /^(file\s*\d+)/ ){ #begin of block $fname = $1; }elsif ($num =~ /E0/ ){ #end of block $all{$fname}={%data}; %data=(); } else { ##data lines my ($k,$v) = $kv_func{$fname}->($line); $data{$k}= exists($data{$k}) ? $data{$k}+$v : $v; } } } print Dumper \%all; __DATA__ file 1 2 1 AB 1.0 2 2 AB-1 2.0 4 1 AB-4 1.0 4 2 AB-6 2.0 a never comes here... file 2 21 01 AB 4.0 22 12 AB-1 6.0 41 44 AB-4 9.0 42 46 AB-6 4.0 42 46 AB-6 4.0 file 3 01 10 AB 4.0 20 02 AB-1 6.0 40 04 AB-4 9.0 02 26 AB-6 4.0 file 4 56 01 AB 4.0 56 12 AB-1 6.0 65 44 AB-4 9.0 65 46 AB-6 4.0 file 5 1 A B 12.00 2 C D 13.00 3 E F 11.00 4 G H 22.00
In reply to Re^3: Perl - Hashes
by remiah
in thread Perl - Hashes
by Perlseeker_1
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |