First off, "we are trying to increment an undef, which is not possible". This is not the case, for example: perl -e '$_ = undef; print ++$_' does in fact print 1. Undef is treated as 0 in a numerical context. Since the for loop hits the undefs, they get incremented to 1.

Similarly, for the map, I have:

$ perl -e '$a = [undef, undef, 3]; map {$_++} @$a; print "@$a"' 1 1 4

Which is the expected result. If you want undef values to be ignored, put an explicit test. I.E. $_++ if defined $_; Also, map in a void context?

Update: Well, you're right, if you create your array your way, it is an attempt to modify a non-existant element. I suggest you just not use the map in a void context. Instead of map {$_++} @a; do @b = map {$_+1} @a; which is safer.


In reply to Re: "Sparse" Array behavior with "for" and "map" by roju
in thread "Sparse" Array behavior with "for" and "map" by Excalibor

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.