Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Hash value printing... WITH ARRAYS *dun dun dun*

by kcott (Archbishop)
on Feb 06, 2012 at 23:46 UTC ( [id://952185]=note: print w/replies, xml ) Need Help??


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:

  • You can remove much of the punctuation-noise by using => (called the fat comma) and qw{} (quote-on-whitespace): foo => [qw{fool food foot}]
  • Unless you really need a hashref, just use a hash: my %primaryFeatures = (...); and later each(%primaryFeatures)
  • While there are many ways to do this, while and each are probably not the best choices here (I think you've probably guessed as much already) - for and keys would be better.
  • Add use strict; and use warnings; to the top of your code.

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://952185]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-19 21:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found