Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Returning an array gives some nice benefits:</p> <pre><code>my @foo = get_array(); # Get list and assign to array. my $foo = get_array(); # Get magnitude of list. my ($f1, $f2) = get_array(); # Get first two members of list. my ($f3,$f6) = (get_array())[3,6]; # Get specific members of the list. sub get_array { my @array = 0..9; return @array; } </code></pre> <p>If you return array refs, you'll have to write several subs to do the same work. Also, an empty array returns false in a boolean context, but an empty array ref does not.</p> <pre><code>if ( get_array() ) { do_stuff(); } </code></pre> <p>If you return array refs, then you have to do:</p> <pre><code>if ( @{ get_array_ref() } ) { do_stuff(); } </code></pre> <p>Except if get_array_ref() fails to return a ref, say instead and undef value, you have a program halting crash. One of the following will help:</p> <pre><code>if ( @{ get_array() || [] } ) { do_stuff(); } if ( eval{ @{get_array()} } ) { do_stuff(); } </code></pre> <p>So if the speed benefits are needed or if you need an array ref (perhaps you want to allow direct manipulation of an object's collection element--yuck, but sometimes it must happen), return an array ref. Otherwise, I find the benefits of standard arrays worth preserving.</p> <p><b>Update:</b> It is really important to remember that what you return from a routine is not always an array or a list. What you return is whatever follows the <code>return</code>, or the result of the last operation. Your return value will be evaluated in context. Most of the time, everything will be fine, but sometimes you can get unexpected behavior. </p> <pre><code>sub foo { return $_[0]..$_[1]; } my $a = foo(9,20); my @a = foo(9,20); print "$a\n"; print "@a\n"; </code></pre> <p>Compare with:</p> <pre><code>sub foo { my @foo = ($_[0]..$_[1]); return @foo; } my $a = foo(9,20); my @a = foo(9,20); print "$a\n"; print "@a\n"; </code></pre> <p>So, when you say "return an array" be sure you really mean "return an array". Be aware of what you return from your routines.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload