Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona
Just another Perl shrine
 
PerlMonks  

Comment on

( #3333=superdoc: print w/ replies, xml ) Need Help??

One thing that has bugged me in a while is the fact that context propagates in Perl in ways that can sometimes lead to surprising results if you haven't realised what's going on. I haven't actually tripped over this particular problem as I was aware of it to begin with, but I'm not sure what the best way to solve it would be:

I'm building a list to return in a function, and naturally I'm storing it in an array. This function is meant to be called with any number of parameters, map each of them to a result, and return the pile. In this particular case, I'm passing CGI parameter names and an untaint spec for each. Obviously I'm often assigning the results to a fresh batch of lexical variables and of course sometimes I want to call it with just a single parameter. There's the quandary:

sub foo { my $num = shift; my @arr = (42)x$num; return @arr; } my $x = foo(1); print $x;
The result is 1 of course because that's the number of elements in @arr - the value an array evaluates to in scalar context, which I established by omitting the parens on the my. The only clean and robust solution I can think of is somewhat awkward: return wantarray ? @arr : $arr[0];
Am I missing any simpler idiom?

Makeshifts last the longest.


In reply to Context aware functions - best practices? by Aristotle

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!
  • 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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            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.
  • Log In?
    Username:
    Password:

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

    How do I use this? | Other CB clients
    Other Users?
    Others drinking their drinks and smoking their pipes about the Monastery: (12)
    As of 2014-04-18 16:49 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      April first is:







      Results (470 votes), past polls