in reply to Re: Using Subroutine Returns
in thread Using Subroutine Returns
This is not a general solution for interpolating subroutines. Whether you use "${\foo()}" or "@{[foo()]}", foo() will be running in list context. In contrast, foo() . '...' and "$username" both run in scalar context.
If the return value is context sensitive, the list context value will be returned instead of the expected scalar context value, as this code snippet demonstrates:
sub foo { wantarray() ? 10 : 1; } print 'Scalar context: '; print ''. foo(); print ', '; print foo() . "\n"; print 'List context: '; print "@{[foo()]}, "; print "${\foo()}\n"; # outputs Scalar context: 1, 1 List context: 10, 10
To preserve the scalar context without stuffing the return value into a variable, one must use concatentation, e.g. '' . foo() or "mumble " . foo() . " the burrowgroves" (or forced scalar context as ig points out below).
Best, beth
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Using Subroutine Returns
by ig (Vicar) on Apr 23, 2009 at 05:10 UTC |