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.
-
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.
|