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


In reply to Re: Hash value printing... WITH ARRAYS *dun dun dun* by kcott
in thread Hash value printing... WITH ARRAYS *dun dun dun* by jaydstein

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.