On 01/25/2016 05:13 PM, lee wrote:
Paul Johnson <p...@pjcj.net> writes:

On Mon, Jan 25, 2016 at 12:24:04AM +0100, lee wrote:
Paul Johnson <p...@pjcj.net> writes:
[...]
Consider with these examples that an expression like (1, 3) might
unexpectedly evaluate to 3, and you start to think that you don't like
things like


sub s {
     my $a = 1;
     my $b = 3;

    return ($a, $b);
}


anymore because you could, by mistake (or intentionally), write


my $x = s;


.  So let me re-phrase my original question to: How do you /safely/
return arrays?

That means I need an error message for '$x = s;' because I'd write that
only by mistake.
You could add to your subroutine:

   die "Only call in list context" unless wantarray;
Oh, that's really cool :)

IMHO, this is pretty cool too:

return wantarray() ? ($a, $b) : [$a, $b];

In a list context, you get back a list.. otherwise you get back a reference to a list. Might not be what you want, though.

Works with arrays, too..

my @anarray = (....)
return wantarray() ? (@anarray) : [@anarray];

Nathan

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to