"This is a snippet I came up with as a response for
someone's weird post..."
That would be How to create multiple keys in a hash, please don't be afraid to link
around here, it gives context to your snippet.
My usually complaints follow: please use strict and warnings
when you post code to the Monastery. Not because we think
you don't know what you are doing, but because you are
posting this code for others to use and review. You should
at the very least declare your variables first. Here is
a rewrite just to show you a more idiomatic way of doing
what you have done. The main differences are declaring and
populating the hash in one line and getting rid of the
unnecessary C-style for loop:
use strict;
use warnings;
# two sample entries, notice i moved this comment
my %modhash =
(
'first:second:third' => [ qw(bob bill bo) ],
'Canada:USA:China' => [ qw(beaver eagle Mao) ],
);
for my $key ( keys %modhash )
{
my @subkeys = split( /:/, $key );
for my $i (0..$#subkeys)
{
print "subkey-> $subkeys[$i]\t",
"subvalue-> $modhash{$key}->[$i]\n";
}
print "\n";
}
But, now that we have this, how are we supposed to find
out the value for say, Canada ... by itself? Ughhh ...
suddenly this code seems unecessary. What advantage is there
to grouping keys together if they don't point to the same
data? In this case, they do point to the same data, but that
data itself is to be split to find the right element. Total
overkill, we could just use this instead:
my %hash =
(
first => 'bob',
second => 'bill',
third => 'bo',
Canada => 'beaver',
USA => 'eagle',
China => 'Mao',
);
Grouping multiple keys and multiple values in the manner
you have really makes no sense. (But that's OK -- the
original question made no sense either!) If we need to group keys
together so that they give the same value, we can use
another hash that is tied to something like
Tie::RangeHash:
use Tie::RangeHash;
tie my %rhash, 'Tie::RangeHash';
%rhash =
(
'first,second,third' => 1,
'Canada,USA,China' => 2,
);
print $rhash{'second'},$/;
print $rhash{'China'},$/;
Now we can use the tied hash and the regular hash
together to achieve our goal ... which i still haven't
figured out. ;)
jeffa
L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)
|