Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Did I get what I expected (an array)?

by arturo (Vicar)
on Jul 16, 2002 at 16:13 UTC ( [id://182135]=note: print w/replies, xml ) Need Help??


in reply to Did I get what I expected (an array)?

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-03-28 21:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found