in reply to Counting Data in two columns?
For me the next stage is working with a 2-column set of data:
my %eats = ( Tom => [ qw( apple orange pear ) ], David => [ qw( mango apple ) ], ); foreach my $eater (keys %eats) { my $fruits = $eats{$eater}; foreach my $fruit (@$fruits) { printf("%-6s %s\n", $fruit, $eater); } }
How would I go about creating a program that outputs:
You could create a hash with fruit for key and a list of persons for value.
sub nice_list { return '' if @_ == 0; return shift if @_ == 1; my $last = pop; return join(', ', @_) . " and $last"; } my %is_eaten_by = ( apple => [ qw( Tom David ) ], orange => [ qw( Tom ) ], pear => [ qw( Tom ) ], mango => [ qw( David ) ], ); foreach my $fruit (keys %is_eaten_by) { my $eaters = $is_eaten_by{$fruit}; my $num_eaters = @$eaters; my $s = $num_eaters == 1 ? 's' : ''; my $p = $num_eaters == 1 ? '' : 's'; print("$num_eaters person$p eat$s ${fruit}s: ", nice_list(@$eaters), "\n"); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Counting Data in two columns?
by sdslrn123 (Novice) on Jun 15, 2006 at 13:52 UTC | |
by neniro (Priest) on Jun 15, 2006 at 14:00 UTC | |
by sdslrn123 (Novice) on Jun 16, 2006 at 21:51 UTC | |
by neniro (Priest) on Jun 16, 2006 at 22:15 UTC | |
|
Re^2: Counting Data in two columns?
by sdslrn123 (Novice) on Jun 21, 2006 at 10:56 UTC | |
by ikegami (Patriarch) on Jun 21, 2006 at 15:29 UTC |