(return; with no arguments does indeed return an empty list in list context, but undef in scalar context, which is very different from the usual false value.)$ perl -w sub nothing { return; } sub something { return 0 == 1; } my @foo; push @foo, nothing(); print "foo has " . @foo . " elements after pushing nothing.\n"; push @foo, something(); print "foo has " . @foo . " element after pushing something.\n"; __END__ foo has 0 elements after pushing nothing. foo has 1 element after pushing something.
The easiest way is to use the not-not operator; given your example:
Some people prefer:sub foo { return !! shift->{some_obj}->some_method; }
and I can see an argument being made for having the false return value be either 0 or "", not both. But just using !! is convenient.sub foo { return ( shift->{some_obj}->some_method ) ? 1 : 0; }
If you actually do want nothing for false in a list context, do
orsub foo { return ( shift->{some_obj}->some_method ) ? 1 : (); }
if true values other than 1 are permissable.sub foo { return shift->{some_obj}->some_method || (); }
In reply to Re: Elegant way to return true or nothing from a subroutine?
by ysth
in thread Elegant way to return true or nothing from a subroutine?
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |