This is a hash of hash references that contain array references. (I think ;)

To print them out, you have to dereference the entire structure as an array. See the full sample program below for further details on this dereferencing and accessing individual elements.

say @{ $An{$id}->{b} };

I couldn't find the original thread, so I have no idea what is in the lettered arrays, so I just threw something together as an example:

#!/usr/bin/perl use warnings; use strict; use 5.10.0; my @bb = ( 41..60 ); my @cc = ( 21..40 ); my @IDs = ( 1..20 ); my %An; my $idx = 0; foreach my $n (@IDs) { push @{$An{$n}->{b}} , $bb[$idx]; push @{$An{$n}->{c}} , $cc[$idx]; $idx++; } # $An{$id}->{b} is an array reference. # To access its elements, we must dereference it # by encompassing the data structure within the # array dereferencing operator: @{} # to iterate over the entire array reference # note the @{} block surrounding the data structure say map { $_, ' ' } @{ $An{1}->{b} }; # to print out a single element of the aref say @{ $An{1}->{b} }[0]; # to print out the zeroeth element contained # in the 'b' value of each %An ID key: for my $id ( @IDs ){ say @{ $An{ $id }->{ b } }[0]; }

As for your other question, you should always declare your variables in the smallest scope possible... ie. as close to the block you are going to use them in, and where possible, within the block you'll use them in. Having a whole boatload of variables declared needlessly at the top of the program is both unsightly and makes for hard to follow code.


In reply to Re: Print elements of hash references by stevieb
in thread Print elements of hash references by Anonymous Monk

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.