Your case may be exceptional but, most often, the right thing to do is just return the array. That allows the user to get behavior he is already familiar with from dealing with plain old arrays.
sub foo {
my @r = (42) x $_[0];
return @r;
}
my @a = foo(3);
my $s = foo(3);
my ($sl)= foo(3);
print "\@a: @a\n";
print "\$s: $s\n";
print "\$sl: $sl\n";
my @t = (42,42,42);
@a = @t;
$s = @t;
($sl) = @t;
print '-'x40,"\n";
print "\@a: @a\n";
print "\$s: $s\n";
print "\$sl: $sl\n";
__END__
@a: 42 42 42
$s: 3
$sl: 42
----------------------------------------
@a: 42 42 42
$s: 3
$sl: 42
Consequently, in most cases, I think that if a user wants to call a function that is documented to return a list and assign it directly to a scalar, it is fair to ask him to remember what he is doing. By the way, I don't think the right way to do that is
my ($x) = foo(1);
but rather
my $x = (foo(1))[0];
The results may be the same but, though the latter is more verbose, it makes the
desired result obvious. It doesn't look like it might have been a mistake.
All of that said, I think using wantarray is probably the right way to do it in your case. It seems unlikely that someone would want to evaluate the returned list in scalar context to get the number of elements, so you are using the facilities Perl provides to get more useful behavior out of your function.
-sauoq
"My two cents aren't worth a dime.";
-
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.