in reply to hash with identical keys

What about a HoH's, letting you store a count using the fruit as a key into a hash based on name, e.g.
use Data::Dumper; my %islanders; while (<DATA>) { chomp; my ($key, $cnt, $fruit) = split / /; $key =~ s/://g; $islanders{$key}{$fruit} += $cnt; } print Dumper(\%islanders); __DATA__ Gilligan: 1 coconut Skipper: 3 coconuts Gilligan: 1 banana Ginger: 2 papayas Professor: 3 coconuts MaryAnn: 2 papayas
I think this approach could work equally as well? Yielding, ...
$VAR1 = { 'Ginger' => { 'papayas' => '2' }, 'Gilligan' => { 'banana' => '1', 'coconut' => '1' }, 'Skipper' => { 'coconuts' => '3' }, 'MaryAnn' => { 'papayas' => '2' }, 'Professor' => { 'coconuts' => '3' } };

---
s;;:<).>|\;\;_>?\\^0<|=!]=,|{\$/.'>|<?.|/"&?=#!>%\$|#/\$%{};;y;,'} -/:-@[-`{-};,'}`-{/" -;;s;;$_;see;
Warning: Any code posted by tuxz0r is untested, unless otherwise stated, and is used at your own risk.

Replies are listed 'Best First'.
Re^2: hash with identical keys
by props (Hermit) on Dec 07, 2007 at 21:33 UTC
    Hi Monks this is my code and it works. I ended up using the sub because of the many "explicit package name" errors . Is there a way to avoid the sub ?
    use warnings; use strict; use Data::Dumper; sub foo { my %hash = (); while (<DATA>) { chomp; my ( $name, $cnt, $item ) = split / /; $name =~ s/://g; $hash{$name}{$item} += $cnt; } return \%hash; } my $rhash = foo(); for my $k1 ( sort keys %$rhash ) { for my $k2 ( sort keys %{ $rhash->{$k1} } ) { open( FILE, ">>$k1.info" ); print FILE " $k1: $rhash->{$k1}{$k2} $k2 \n"; } } __DATA__ Gilligan: 1 coconut Skipper: 3 coconuts Gilligan: 1 banana Ginger: 2 papayas Professor: 3 coconuts MaryAnn: 2 papayas