Hi All,
  I use nested data strcutures quite a lot, and can easily end up with arrays, inside hashes, inside arrays, etc. Now when I'm looping through I like to use foreach as it makes the notation shorter. For example:-
my $ref; $ref = [ { "key1" => 'a', "key2" => 'b', }, { "key1" => 'c', "key2" => 'd', }, ]; foreach $hashref (@{$ref}) { print $hashref->{'key1'}; }#foreach
  Now I sometimes I want to know the array item number so I end up doing a for:-
for (my $item = 0; $item <= $#{$ref}; $item++) { print $item; print $ref->[$item]->{'key1'}; }#for
As you can see the print is much longer, when the data structure is more complex this can be a really big difference.
Is there a good way of getting the benefits of the notation in the first example while knowing the array item number. Is it safe to:-
my $item = 0; foreach $hashref (@{$ref}) { print $hashref->{'key1'}; $item++; }#foreach
Most the time the data is loading from files and I do not know how the foreach loop with deal with missing array items, such as:-
my $ref; $ref->[0]->{'key1'} = "a"; $ref->[5]->{'key1'} = "b"; my $item = 0; foreach $hashref (@{$ref}) { print $item; print $hashref->{'key1'}; $item++; }#foreach

Having written this, I realized I could answer my own questions simply by testing the final code example, perl does indeed fill in any missing array items producing the result I expected. I thought I'd post this anyway encase others have similar questions, or I'm sure there might be some interesting comments.

Lyle

In reply to looping through array references by cosmicperl

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.