Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Re: Re: array or scalar, that's the question

by Fastolfe (Vicar)
on Jan 02, 2002 at 00:13 UTC ( [id://135542]=note: print w/replies, xml ) Need Help??


in reply to Re: Re: array or scalar, that's the question
in thread array or scalar, that's the question

Differentiating between a "scalar" and an "array" is meaningless here. When you say "return @bar" Perl flattens @bar into a list.
$foo = 3; @bar = (1, 2, 3); return $foo; # (3) return @bar; # (1, 2, 3)

In a scalar context, both of these versions will return 3 (the last element in the list returned). In a list context, you get 3 or 1, 2, 3. Just returning @bar, though, is sufficient for both cases, because it's your calling code that would want to act on the results. Make sense?

If you're wanting to return a real solid array (so that you can return @foo, @bar without flattening it into one big list), you need to return references to each array.

return (\@foo, \@bar); ... my ($fooref, $barref) = your_function();

Replies are listed 'Best First'.
Re: Re: Re: Re: array or scalar, that's the question
by Juerd (Abbot) on Jan 02, 2002 at 00:21 UTC
    When you say "return @bar" Perl flattens @bar into a list.
    That's what happens in _list_ context. If the sub is called in scalar context, @bar will also be in scalar context and thus return the number of elements in @bar.

    sub foo { my @foo = qw(a b c d); return @foo; } sub bar { return qw(15 4 3 12); } print foo(), "\n"; # list context => abcd\n print scalar foo(), "\n"; # scalar context => 4\n print bar(), "\n"; # list context => 154312\n print scalar bar(), "\n"; # scalar context => 12\n

    Explanation: a list returns its last element in scalar context, an array returns the number of elements in scalar context.

    2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

      You're right, I was being a bone-head. The '3' my examples returned wasn't the 3rd element, it was the fact that there were 3 elements in the array.

      So yes, there is a very important distinction, but if anything, it's another case for not differentiating between a "scalar" and an "array" in the function, because with one element, a scalar context returns that one element, whereas multiple elements will get returned as an array, causing a scalar context to return the number of items in that array. This change in behavior is probably undesirable.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://135542]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2024-04-16 10:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found