in reply to Elegant way to return true or nothing from a subroutine?

Does this fit what you're looking for?

sub foo { return shift->{some_obj}->some_method ? 1 : undef; }


--chargrill
s**lil*; $*=join'',sort split q**; s;.*;grr; &&s+(.(.)).+$2$1+; $; = qq-$_-;s,.*,ahc,;$,.=chop for split q,,,reverse;print for($,,$;,$*,$/)

Replies are listed 'Best First'.
Re^2: Elegant way to return true or nothing from a subroutine?
by Anonymous Monk on Oct 10, 2006 at 02:00 UTC

    undef isn't the same as "nothing":

    #!/usr/bin/perl -w use strict; sub ret_undef { return undef } sub ret_nothing { return; } print ret_nothing(), "\n"; print ret_undef(), "\n"; my @foo = ret_nothing(); print "Elements in foo: ", scalar @foo, "\n"; print @foo; my @bar = ret_undef(); print "Elements in bar: ", scalar @bar, "\n"; print @bar;

      Are you sure? Consider:

      use strict; use warnings; use Data::Dump::Streamer; my $value = undef; print !!$value; my $nothing = nothing (); my $retNothing = retNothing (); my $retUndef = retUndef (); my $retFalse = retFalse (); my $retFalse2 = -retFalse (); Dump (\$nothing); Dump (\$retNothing); Dump (\$retUndef); Dump (\$retFalse); Dump (\$retFalse2); sub nothing { } sub retNothing { return; } sub retUndef { return undef; } sub retFalse { return 1 == 0; }

      Prints:

      $SCALAR1 = \do { my $v = undef }; $SCALAR1 = \do { my $v = undef }; $SCALAR1 = \do { my $v = undef }; $SCALAR1 = \do { my $v = '' }; $SCALAR1 = \do { my $v = 0 };

      Updated to add two false cases

      and in list context :)

      ... my @nothing = nothing (); my @retNothing = retNothing (); my @retUndef = retUndef (); my @retFalse = retFalse (); my @retFalse2 = -retFalse (); Dump (\@nothing); Dump (\@retNothing); Dump (\@retUndef); Dump (\@retFalse); Dump (\@retFalse2); ...

      Prints:

      $ARRAY1 = []; $ARRAY1 = []; $ARRAY1 = [ undef ]; $ARRAY1 = [ '' ]; $ARRAY1 = [ 0 ];

      DWIM is Perl's answer to Gödel

        Try it in list context.