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

In reply to Re^4: Scoping question by BrowserUk
in thread Scoping question by Dr. Mu

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.