AnomalousMonk has asked for the wisdom of the Perl Monks concerning the following question:

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?

Replies are listed 'Best First'.
Re: unpack Group Repeat-Count Behavior: Scalar versus List Context
by chuckbutler (Monsignor) on Mar 02, 2010 at 01:49 UTC

    On Win32 5.10.1 (ActiveState 1006), I can reproduce the same result.

    As a work-around, using the fact that we wish to print the fourth value, skipping 12 bytes:

    . . . my $unk = '(x12) N'; . . .
    This produces:
    n1 44 n2 44
    Good luck. -c

Re: unpack Group Repeat-Count Behavior: Scalar versus List Context
by jethro (Monsignor) on Mar 02, 2010 at 00:26 UTC

    perl 5.10.0 on linux prints

    n1 44 n2 44

      Same with v5.8.8 built for x86_64-linux-gnu-thread-multi (update: and v5.10.0 built for x86_64-linux),  but v5.10.1 built for x86_64-linux prints

      n1 22 n2 44

      => conclusion so far:  odd minor versions exhibit the problem ;)