seaver has asked for the wisdom of the Perl Monks concerning the following question:

Dear all,

Lets say I want to do this:

sub test{ my $result = $object->createNewObject(); if($result){ push @results, $result; return $result; }else{ return undef; } }
How far could this be condensed?

Cheers
Sam

Replies are listed 'Best First'.
Re: Condensing code...golfing with push and return
by Aristotle (Chancellor) on Oct 10, 2003 at 17:35 UTC
    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.

      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.

Re: Condensing code...golfing with push and return
by BrowserUk (Patriarch) on Oct 10, 2003 at 23:12 UTC

    You could do

    sub test { return ($results[ @results ] = $object->createNewObject() ) || pop @results; }

    which I think is syntactically equivalent to your original. Whether you would want to is another matter :)


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail