Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

comment on

( [id://3333]=superdoc: 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:

#!/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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-03-29 08:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found