Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re^3: Perl - Hashes

by remiah (Hermit)
on Oct 14, 2013 at 08:33 UTC ( #1058146=note: print w/ replies, xml ) Need Help??


in reply to Re^2: Perl - Hashes
in thread Perl - Hashes

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


Comment on Re^3: Perl - Hashes
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1058146]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (16)
As of 2014-08-27 13:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (238 votes), past polls