in reply to Context aware functions - best practices?
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
but rathermy ($x) = foo(1);
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.my $x = (foo(1))[0];
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.";
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Context aware functions - best practices?
by MarkM (Curate) on Jan 15, 2003 at 07:17 UTC | |
by sauoq (Abbot) on Jan 15, 2003 at 22:47 UTC | |
by ihb (Deacon) on Jan 15, 2003 at 20:05 UTC | |
by sauoq (Abbot) on Jan 15, 2003 at 22:56 UTC | |
by Aristotle (Chancellor) on Jan 15, 2003 at 23:55 UTC |