in reply to Re: variable set to 0 ? 0 : 1
in thread variable set to 0 ? 0 : 1
Returning zero in Perl is usually a bad meme. It is ok if you actually meant to return a numeric zero, but if you mean to return "false", the Perlish way is to return an empty list. This is because by returning 0 you return a single-element list, which evaluates to true in list context. The code would then look like this:
The opposite could be argued just as easily: if you return an empty list to mean "false", the false-ish-ness could be lost (or other problems could arise) if your return value is "slurped" into another list context.
Consider...
#!/usr/local/bin/perl -wl use strict; sub a_func_that_returns_false { return 0; } sub your_func_that_returns_false { return (); } sub func_that_expects_string_boolean_and_num { my $str = shift; my $bool = shift; my $num = shift; print "CALLED FUNC: ", $str; print " bool was ", ($bool ? "true" : "false"); print " num was ", (20 < $num ? "bigger" : "smaller"), " then tw +enty"; } &func_that_expects_string_boolean_and_num ("the zero way", &a_func_that_returns_false(), 42); &func_that_expects_string_boolean_and_num ("the empty list way", &your_func_that_returns_false(), 42); __DATA__ laptop:~> monk.pl CALLED FUNC: the zero way bool was false num was bigger then twenty CALLED FUNC: the empty list way bool was true Use of uninitialized value in numeric lt (<) at monk.pl line 12. num was smaller then twenty
Bottom line: there's no substite for using wantarray
to check your calling context, and acting appropriately
(except perhaps extensively documenting that your method may
not work the way people think and making it their
responsibility to force the calling context)
Update: good point blakem
|
---|
Replies are listed 'Best First'. | |
---|---|
Re3: variable set to 0 ? 0 : 1
by blakem (Monsignor) on Sep 06, 2002 at 08:31 UTC |