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 | |
|
Re: unpack Group Repeat-Count Behavior: Scalar versus List Context
by jethro (Monsignor) on Mar 02, 2010 at 00:26 UTC | |
by almut (Canon) on Mar 02, 2010 at 00:37 UTC |