One of the interesting things about Perl is that what a subroutine returns is determined by the context in which it is called:

#!/usr/bin/perl use warnings; use strict; sub foo { my @water = qw(heavy normal polluted); @water; } my $bar = foo(); my @baz = foo(); print "Bar : $bar\n"; print "Baz : @baz\n";

with "bar", the interpreter sees that it's assigning the returned value to a scalar (the call is made in scalar context), so it gives you the size of the list it returned -- as a matter of fact, you'd get the same result with  my $bar = scalar foo();, so your code isn't doing what you expect. With "baz", it sees that it's assigning the returned value to an array (list context), so it assigns the members of the list it's returning to the array. (BTW, this sort of behavior is changing radically in Perl 6). If your sub returns a scalar, and you assign it to an array, what you get is a one member array. So, to a large extent, you get what you ask for from the subroutine. Perl (v. 5, anyway =) just isn't the kind of language that tries to enforce the distinction you're looking to enforce.

By the way, you can check for the calling context within the subroutine with wantarray. HTH

I mistrust all systematizers and avoid them. The will to a system shows a lack of integrity -- F. Nietzsche


In reply to Re: Did I get what I expected (an array)? by arturo
in thread Did I get what I expected (an array)? by bronto

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.