![]() |
|
Clear questions and runnable code get the best and fastest answer |
|
PerlMonks |
Re: Did I get what I expected (an array)?by arturo (Vicar) |
on Jul 16, 2002 at 16:13 UTC ( #182135=note: print w/replies, xml ) | Need Help?? |
One of the interesting things about Perl is that what a subroutine returns is determined by the context in which it is called:
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 Section
Seekers of Perl Wisdom
|
|