http://www.perlmonks.org?node_id=226916

Aristotle has asked for the wisdom of the Perl Monks concerning the following question:

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.