in reply to Use of wantarray Considered Harmful
Which way "just works"?At $work right now, you can find both of these:
return wantarray ? @x : \@x; return wantarray ? @x : $x[0];I wonder what will happen when one of those two programmers has to work on the other's code.
Both are just bad practice.
That's not something wantarray is to blame for. Both obscure the intent of the calling code and place the usage intention of the function return to that function, out of the wrong type of laziness.
It is so much clearer to make the intent clear in the calling code,
my $ref = [ $foo -> bar( $stuff) ]; my @ary = $foo -> bar( $stuff); my $baz = ( $foo -> bar( $stuff) )[0];
which usage doesn't even need comments.
If the code of the method bar() produces a list, it should return a list and leave it to the caller to handle the result: stuff it into a reference, an array, place the first element in a scalar or count the list's elements. Things get interestingly different if the semantics and/or return values of the function in question are non-trivially different in scalar, list or void context, for purposes made clear in the calling code.
But then,
I didn't think context mattered
...or I didn't know I changed the context.
context is a basic perl principle and built into the language, for good reasons, hence there's wantarray as a built-in function which is absolutely needed. Bad usage is no reason to deprecate it.
Core perl functions behave different when called in scalar or list context, and such behavior is documented. Your code examples just show the lack of documented conventional coding standards at your working place, which wantarray isn't to be blamed for, either. If you have dual-use functions or methods, you have them documented, and are aware of the context of the calling code.
wantarray has its good uses - Contextual::Return relies on it.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Use of wantarray Considered Harmful (bad use)
by BrowserUk (Patriarch) on Dec 12, 2008 at 20:32 UTC | |
by shmem (Chancellor) on Dec 13, 2008 at 01:53 UTC | |
by BrowserUk (Patriarch) on Dec 13, 2008 at 08:55 UTC | |
Re^2: Use of wantarray Considered Harmful (bad use)
by kyle (Abbot) on Dec 12, 2008 at 19:30 UTC | |
by shmem (Chancellor) on Dec 13, 2008 at 01:09 UTC | |
Re^2: Use of wantarray Considered Harmful (bad use)
by TGI (Parson) on Dec 12, 2008 at 21:06 UTC | |
by Porculus (Hermit) on Dec 12, 2008 at 22:52 UTC | |
by TGI (Parson) on Dec 15, 2008 at 08:03 UTC |