in reply to Hash value printing... WITH ARRAYS *dun dun dun*
The format of a hash is basically (key, value, key, value, etc.) so, despite adding the parentheses, what you are doing here is mapping foo to fool, food to foot and bar to barricade. An arrayref (reference to an array) is a single value and that's what you should be using here. So, your code becomes:
my $primaryFeatures = { 'foo', ['fool', 'food', 'foot'], 'bar', ['barricade'], };
You'll need to dereference the arrayref (i.e. @$value) and print each element in some sort of loop. Simplistically, change the print statement to something like:
for my $element (@$value) { print "($key, $element)\n"; }
That should get the code doing what you want. In addition, here's a few other suggestions:
Putting all that together, your code might look like:
use strict; use warnings; my %primaryFeatures = ( foo => [qw{fool food foot}], bar => [qw{barricade}], ); for my $key (keys %primaryFeatures) { for my $element (@{$primaryFeatures{$key}}) { print "($key, $element)\n"; } }
each(), keys() and values() do not guarantee the order of data returned. If you want the exact order you've shown above, you'll need additional code. On my machine, this code outputs:
(bar, barricade) (foo, fool) (foo, food) (foo, foot)
Finally, what I have here is not so much the correct answer but rather one of many possible working solutions. On this site and in Perl books and documentation you'll often come across the Perl motto: TMTOWTDI (There's more than one way to do it).
-- Ken
|
|---|