in reply to Re^2: Scoping question
in thread Scoping question

I do like this one a lot because, even though I have access to grid, it's called elsewhere where a scalar result is expected. The "|| ( )" makes for an elegant one-liner that eliminates the temporary variable completely. Thanks! And many thanks to all of you for the thoughtful discussion!

Replies are listed 'Best First'.
Re^4: Scoping question
by BrowserUk (Patriarch) on Nov 04, 2004 at 07:25 UTC

    Making grid() return the empty list will do the right thing in a scalar context too.

    #! perl -slw use strict; sub grid{ return $_[0] ? 12345 : (); } my @array = 1 .. 4; print "@array"; push @array, grid( 1 ); print "@array"; push @array, grid( 0 ); print "@array"; my $item = grid( 0 ); print 'The null list does the right thing in a scalar context' if not defined $item; __END__ [ 7:10:52.28] P:\test>junk 1 2 3 4 1 2 3 4 12345 1 2 3 4 12345 The null list does the right thing in a scalar context

    It avoids the temp var and the need to code the conditional at every use by moving the replicated code inside the subroutine where it belongs.

    You could also use wantarray to test the context and return wantarray ? () : undef; but that's completely unnecessary also.

    The very simplest thing to do when there is nothing to return is just return:

    sub grid { my( $x, $y ) = @_; if( outOfRange( $x) or outOfRange( $y ) { return; else { # determine return value... return $rv; } }

    When Perl encounters the empty return, it determines the context and return the appropriate value for you. Some people don't like that though.


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon