in reply to Condensing code...golfing with push and return

sub test { my $result = $object->createNewObject() || return; push @results, $result; return $result; }
More readable, too. Shorter gets less readable:
sub test { push @results, $object->createNewObject() || return; return $results[-1]; }

Makeshifts last the longest.

Replies are listed 'Best First'.
Re: Re: Condensing code...golfing with push and return
by liz (Monsignor) on Oct 10, 2003 at 17:46 UTC
    One note:

    The original code had return undef, your code has just return. They are not the same.

    A bare return is basically equivalen to:

    return wantarray ? () : undef;
    your solution is equivalent to:
    return wantarray ? (undef) : undef;
    i.e. returns an array with a single element with an undefined value. As opposed to an empty array.

    Liz

      Good observation, and it's good you bring it up. The point is that a list with one element evaluates as true. Most people who say return undef or return 0 actually just want to return a false value, not an explicit undef or 0. It's good habit to use an unadorned return to signal falsehood; something as innocent as
      if( my ($obj) = test() ) { # ... }
      can trip you up.

      Makeshifts last the longest.

        No, use the proper return type for the proper function type. If you return an empty list for false, then you'll be tripped up by something as simple as:

        my %hash= ( this => GetThis(), foo => 'bar', baz => 'biff', ); # Which results in: # $hash{this} eq "foo" # ! exists $hash{foo} # $hash{bar} eq 'baz' # ! exists $hash{baz} # exists $hash{biff}
        If your function returns lists, then an empty list is likely the correct thing to return for "false". If your function never returns lists, then I'd have it return a false scalar value not an empty list.

        BTW, my favorite false value is !1 which is a lot like '' except that it won't give a warning if used in a numeric context. (It is what Perl's own functions return for "false but not undefined".)

                        - tye