in reply to Confused Contexts and wantarray

A little experimentation got me the following (somewhat scary) result:

use strict; sub flab { my @r = ( 1 .. 10 ); wantarray ? @r : \@r; } print "flab has ", scalar @{flab()}, " entries\n";
It does work ...

Replies are listed 'Best First'.
Re^2: Confused Contexts and wantarray
by MichaelORourke (Initiate) on Jun 15, 2007 at 20:20 UTC
    Hi folks, New to 'monks but not Perl. I've used it (wantarray) very effectively (>5.6.1, probably well before) in this way.
    sub func { my(...) = @_; my @new_a; # assume some assignment to @new_a based on params for(....) {} wantarray? @new_a: \@new_a; } # this one gets you a reference to @new_a in &func() # which is available as long as $ar_array is in scope my $ar_array = &func(...); # this is the copy of @new_a from &func() # @new_a is gone my @array = &func(...); Also: wantarray? @foo: "@foo" wantarray? @foo: $foo[0] aren't nearly the same except the first above is an implicit join to scalar and the second is the first element which may or may not be what you want.
    Please contact me: morourke@theworld.com
Re^2: Confused Contexts and wantarray
by redlemon (Hermit) on Jan 19, 2005 at 00:58 UTC

    how is this scary?

    @{...} puts flab() in array context so it returns the array @r.

    scalar(...) then evaluates that array in scalar context, returning its size.

    I don't see anything magical in there. (apart from me probably mixing array and lists again)