#! 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
|