I think that I'm missing something fundamental here... isn't for the third element of @array grep {@$_} @arrays yielding grep { 1,2 } @arrays when dereferenced?

I think perhaps the fundamental thing is that in Perl, arrays are different from lists. Lists and the comma operator are one way of several to initialize an array, as in my @array = ("a","b","c");, but once those items are stored in the array, the comma operator is no longer relevant; @array is not the same as the literal expression ("a","b","c") any more, including for dereferenced array references. An array in scalar context returns the number of elements it contains, and grep provides scalar context to its expression, so grep {@$_} @arrays is equivalent to grep {scalar(@$_)} @arrays, and scalar(@$_) yields 2 for the element [1, 2]. That's not because 2 is the last item in the list, but because there are 2 items in the listarray.

In the example code, try replacing @arrays = ( [], [1], [ 1, 2 ], [], [ 5 .. 9 ] ); with @arrays = ( [], ["a"], ["b", "c"], [], ["d".."h"] );, and the functionality will be the same. Then, try replacing it with @arrays = ( [], [0], [0, 0], [], [0,0,0,0,0] ); (a bunch of false values) and it will still work the same. scalar(0,0,0) is false, because it returns the last value of the list, 0, which is false, but my @x=(0,0,0); scalar(@x) is true, because the array @x evaluates to 3. That's how the grep works here.


In reply to Re^5: Perlsecret - plus no-ops by haukex
in thread Perlsecret - plus no-ops 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.