in reply to Re: Condensing code...golfing with push and return
in thread Condensing code...golfing with push and return

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

Replies are listed 'Best First'.
Re^3: Condensing code...golfing with push and return
by Aristotle (Chancellor) on Oct 10, 2003 at 17:58 UTC
    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
        I know; personally, I tend to do something like
        use constant TRUE => 1; use constant FALSE => !TRUE;

        when I'm going to need those a lot (it's sometimes helpful to be able to communicate that you mean "true value" and not "numerical one").

        As for context, you are right; I guess it's a matter of habit. I'd tend to write that hash construction like

        my %hash= ( this => scalar GetThis(), foo => 'bar', baz => 'quux', );
        That's probably CGI.pm's legacy.. :)

        Makeshifts last the longest.