Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Re: variable set to 0 ? 0 : 1

by hossman (Prior)
on Sep 06, 2002 at 07:51 UTC ( [id://195592]=note: print w/replies, xml ) Need Help??


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
    there's no substite for using wantarray to check your calling context
    Interesting example, though I fail to see how wantarray will help in this case:
    sub use_wantarray { return wantarray ? () : 0 }
    Wont work properly in your example either.... Note that the above sub is equivalent* to the recommended way to return false, i.e. simply return:
    sub recommended_way { return; }
    * except when used in void context, but that isn't relevant here.

    -Blake

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://195592]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-03-29 10:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found