Your example code takes a reference to each individual list element returned by foo(), and then retains the last one.

If you want a reference to an array, you have two choices. First, you could modify the subroutine to return a reference to an array:

sub foo { return [0,1]; } my $aref = foo();

Second, you could instantiate an array reference upon receiving the return value of the subroutine:

sub foo { return (0,1); } my $aref = [foo()];

In the second example, the [...] square brackets are creating a reference to an anonymous array that is being populated by the list returned from foo().

For large lists, the first example could be more efficient since it passes a single value (the array reference) back from the subroutine call, rather than a potentially large list which must then be pulled into a new reference. We all love to hate wantarray, but how about this?

sub foo { my @rv = (0,1); return wantarray() ? @rv : \@rv; } my $aref = [foo()]; # wantarray() will be true, so the entire list ge +ts passed back and then the square braces create and populate an arra +y ref. my $aref2 = foo(); # wantarray() will be false, so inside the subrou +tine we return a reference to the array.

Yeah.... that code kind of smells because it has a strong potential of surprising the caller. Just a thought, but you'll probably want the first or second example and just keep the third as an example of something that Perl can do but maybe shouldn't. ;)


Dave


In reply to Re: Reference to return value of a subroutine by davido
in thread Reference to return value of a subroutine by Christina

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.