This reads to me like it is motivated by the all-too-common and deceptively flawed meme...
I think I know better than that (but I can see how someone reading might think otherwise).
sub get_array { my @x = (4, 5, 6); return @x; } sub get_list { return (10, 11, 12, get_array()); } my @as_array = get_list(); my $as_scalar = get_list(); print "last list item: $as_array[-1]\n"; print "list in scalar: $as_scalar\n"; __END__ last list item: 6 list in scalar: 3
Not only that, the context extends to everything in a list after return:
sub context_in_position { my ($position_name) = @_; my $wa = wantarray; my $context; if ( $wa ) { $context = 'list' } elsif ( defined $wa ) { $context = 'scalar' } else { $context = 'void' } print "context in position '$position_name': $context\n"; return; } sub list { return ( context_in_position( 'a' ), context_in_position( 'b' ), ); } print "list() in void:\n"; list(); print "list() in scalar:\n"; scalar list(); print "list() in list:\n"; () = list(); __END__ list() in void: context in position 'a': void context in position 'b': void list() in scalar: context in position 'a': scalar context in position 'b': scalar list() in list: context in position 'a': list context in position 'b': list
I think some Perl programmers might find it pretty surprising that in an expression like ( foo(), bar() ), foo() would find !wantarray(), but that's what happens.
Do you still think I'm missing something here? Really, I want to get this straight, conceptually.
The subroutine does /not/ return an array that then decides to give its size when it finds itself in a scalar context.
I've heard the news that the array finds itself in a scalar context even before it makes it "out the door" to the wild world outside the sub. The context that sub is in seems to extend into the sub, into the place where the return "happens."
That said, it seems blindingly obvious that return @this returns an array! So, here's a question for you. Is there any way to explain what happens, consistently and accurately, if we accept the statement that "return @this returns an array"? I think such an explanation would be far more readily accepted and understood than an explanation that starts with "you can't return arrays."
(As an aside, it is likewise obvious that return IO::File->new() returns "a new IO::File object", but this fits nicely in the "scalar, list, or Nothing" idea because the object is a scalar. But would we say that an array is a list or a scalar? And if we say that an array is a list, how do we explain how it behaves differently from a list in scalar context?)
There are lots of cases where these ideas give the right answer. But the cases where they lead to the wrong answers are surely more important.
I'd be very interested to read some of the cases you refer to.
In reply to Re^4: Evil Interview Questions (memes)
by kyle
in thread Evil Interview Questions
by kyle
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |