in reply to working with a hash
I'd like to also suggest you to lexicalize the fields variables within the while loop scope, since you don't need them outside of the loop.
In more verbose:
my %count; while (...) { my($field1, $field2) = split(...); # assume that we already has the key $field1 in %count # so the value would be $count{$field1}. # # assume it to be array reference, pretend you did: # $count{$field1} = [] # # the push() function requires real array so you need # to dereference it first, like this @{$count{$field1}}, # then push the new value # push @{$count{$field1}}, $field2; }
However, if you want to keep the unique keys to be scalar instead of array reference, you have to check for keys existence.
my %count; while (...) { my($field1, $field2) = split(...); if (exists $count{$field1}) { # force the value to be array ref if it's # not done so $count{$field1} = [$count{$field1}] unless ref $count{$field1}; push @{$count{$field1}}, $field2; } else { $count{$field1} = $field2; # normal assignment } }
On more thing, for simple dumping, I would rather use the straightwoard Dumper() function:
print Dumper(\%count);
Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!
|
|---|