in reply to Scoping question

Variables declared with 'my' only become visible after the current statement has finished (ie. ended with ';'). Thus, under strictures, you must declare the variable on at least the statement before you use it.

I would probably use:

my $item = $self->grid($x, $y); push @{$self->{'select'}}, $item if $item;

Replies are listed 'Best First'.
Re^2: Scoping question
by revdiablo (Prior) on Nov 03, 2004 at 22:55 UTC

    Or, if one really wants to do everything in one line, and the $item variable is not used for anything else:

    push @{ $self->{select} }, $self->grid($x, $y) || ();

    Update: I see Roy Johnson already posted essentially the same code at Re: Scoping question, though he opted to use or with parentheses instead of ||, as I used.

      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!

        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