Foreach loop provides list context, so foreach my $i ( @{ $aref } ) explodes into its elements

foreach my $i( ['kept', 82], ['notkept', 1], ['repaired', 3] ) { ... # so $aref->[$i][0] # looks like $areg->[ ['kept', 82] ][0] #
Here the first lines out error output:
$ perl buggy_array.pl 2> out.txt (it hangs here, press Ctrl-C to stop) $ head -6 out.txt Use of reference "ARRAY(0x1cfb148)" as array index at ary.pl line 21. Use of uninitialized value in concatenation (.) or string at ary.pl li +ne 21. Use of reference "ARRAY(0x1d0fad8)" as array index at ary.pl line 21. Use of uninitialized value in concatenation (.) or string at ary.pl li +ne 21. Use of reference "ARRAY(0x1d0fbf8)" as array index at ary.pl line 21. Use of uninitialized value in concatenation (.) or string at ary.pl li +ne 21.
Now, why does it keep looping?
perl -E 'my $aref=[undef]; say 0 + $aref' 19468616
19468616 is the memory address of $aref here. Which means
$areg->[ ['kept', 82] ][0] # becomes something like # $areg->[ 9999999 ][0] # (or whatever the memory address of that array is...)
When you do stuff like $aref->[999][0] and element 999 of $aref doesn't exist, Perl will extend $aref. It will fill it with undef, up to element 999.
perl -E 'my $aref=[undef]; $aref->[1000][0]; say scalar @{ $aref }' 1001
They call it 'autovivification' (sp?). (but if you do $aref->[999][500], Perl will not create the rightmost array - the one with 500 elements)

So, now your $aref has tons of of undefs. So the loop keeps looping and issuing warnings.

So yeah, all in all, that was a pretty interesting question, I must say.


In reply to Re: Dereference anonymous AoA by Anonymous Monk
in thread Dereference anonymous AoA by neilwatson

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.