Oh, Most Monkilicious Monks:

I have a packed string of integers and wish to index into the string to extract a single integer at a particular offset. I use the 'index-by-size' (e.g., 'x[N]') and group-repetition features of unpack to do this. This works, but  unpack behaves differently in scalar versus list context:

>perl -wMstrict -le "my $ps = pack 'N*', 11, 22, 33, 44, 55, 66; my $upk = '(x[N])3 N'; my $n1 = unpack $upk, $ps; print qq{n1 $n1}; my ($n2) = unpack $upk, $ps; print qq{n2 $n2}; " n1 22 n2 44

The index-by-size works as expected in scalar context, but the repeat count on the indexing sub-template group is just ignored. (The behavior of the example code is the same in ActiveState 5.8.9 and Strawberry 5.10.1, both running under Windows 7.)

I don't understand the reason for the difference in behavior in different contexts. To quote the perlfunc unpack doc (first paragraph, emphasis added):

unpack does the reverse of pack: it takes a string and expands it out into a list of values. (In scalar context, it returns merely the first value produced.)
It seems to me there should be no difference.

Can anyone explain? Is this a feature? Mis-feature? Bug?


In reply to unpack Group Repeat-Count Behavior: Scalar versus List Context by AnomalousMonk

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.