the array (0, 1)

I think this might be the misunderstanding here: (0, 1) isn't an array, in this form it's a literal list. While you obviously use lists to populate arrays, arrays and literal lists behave differently in different contexts. For example, an array in scalar context returns its size, whereas a list returns its last value, and taking a reference to an array creates an arrayref, while taking a reference to a list works as follows.

What is going on here is that your sub foo is returning the list (0, 1), and the \ (backslash) referencing operator is "distributive" when applied to lists, meaning that \(0, 1) is the same thing as (\0, \1). So your assignment basically becomes my $var = (\0, \1);. Then, the Comma Operator in scalar context "evaluates its left argument, throws that value away, then evaluates its right argument and returns that value", which is why $var is being assigned \1.

You could do several things, as the other monks have shown: [foo()], return [0, 1], or also possible would be return \@array. However, note that \ has a special-case behavior which means that sub foo { my @array = (0,1); return @array }; my $var = \(foo()); would not work, as "\(@foo) returns a list of references to the contents of @foo, not a reference to @foo itself." (perlref).

Update: See also this recent thread, the FAQ What is the difference between a list and an array?, and perhaps one or two other PerlMonks threads such as What is the difference between a list and an array?.


In reply to Re: Reference to return value of a subroutine by haukex
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.