in reply to Force 'sub' return to be treated in list context?

You haven't shown us a test case which fails so I'm guessing, but if you write:

my $thing = UnPack (1, $stringpack);

$thing will get a count instead of the "first" element of the returned array because UnPack is called in scalar context. Consider:

use strict; use warnings; my @single = (1); my @many = (1 .. 3); for my $ref (\@single, \@many) { my $count = listy(@$ref); my @elements = listy(@$ref); my ($firstElement) = listy(@$ref); print "Count $count, first: $firstElement, elements: @elements\n"; } sub listy { return @_; }

Prints:

Count 1, first: 1, elements: 1 Count 3, first: 1, elements: 1 2 3

If you write:

my ($thing) = UnPack (1, $stringpack);

I suspect your problem will be resolved. It's not what you return, it's the context that is important and the () provides a list context.

True laziness is hard work

Replies are listed 'Best First'.
Re^2: Force 'sub' return to be treated in list context?
by flexvault (Monsignor) on Apr 04, 2012 at 11:46 UTC

    GrandFather,

    I did show how to use the UnPack, but the following should demonstrate:

    # Use: ## n - number of 64bit pack +ed numbers in string # my @Numbers = UnPack( n, $stringpack ); ## string input, array outp +ut my $pack = pack("N N", 0, 99 ); my $Numbers = UnPack( 1, $pack ); say $Numbers; ( $Numbers ) = UnPack( 1, $pack ); say $Numbers; my @Numbers = UnPack( 1, $pack ); say $Numbers[0]; ( @Numbers ) = UnPack( 1, $pack ); say $Numbers[0]; __END__ result: 1 99 99 99

    On running this code, I could not reproduce my original statement, so I can only assume that I typed "$Numbers" instead of "@Numbers" when I wrote the test cases for 'sub UnPack'. But if I had put parenthesis around the scalar, I still would have gotten what I wanted ( list context ).

    Thank you

    "Well done is better than well said." - Benjamin Franklin