Your example code takes a reference to each individual list element returned by foo(), and then retains the last one.
If you want a reference to an array, you have two choices. First, you could modify the subroutine to return a reference to an array:
sub foo { return [0,1]; } my $aref = foo();
Second, you could instantiate an array reference upon receiving the return value of the subroutine:
sub foo { return (0,1); } my $aref = [foo()];
In the second example, the [...] square brackets are creating a reference to an anonymous array that is being populated by the list returned from foo().
For large lists, the first example could be more efficient since it passes a single value (the array reference) back from the subroutine call, rather than a potentially large list which must then be pulled into a new reference. We all love to hate wantarray, but how about this?
sub foo { my @rv = (0,1); return wantarray() ? @rv : \@rv; } my $aref = [foo()]; # wantarray() will be true, so the entire list ge +ts passed back and then the square braces create and populate an arra +y ref. my $aref2 = foo(); # wantarray() will be false, so inside the subrou +tine we return a reference to the array.
Yeah.... that code kind of smells because it has a strong potential of surprising the caller. Just a thought, but you'll probably want the first or second example and just keep the third as an example of something that Perl can do but maybe shouldn't. ;)
Dave
In reply to Re: Reference to return value of a subroutine
by davido
in thread Reference to return value of a subroutine
by Christina
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |