[Edinburgh-pm] a Perl surprise
Jeff Parsons
bynari at gmail.com
Wed Jul 18 06:36:56 PDT 2012
Hey,
I'd have expected the 8, yeah.
It's because there's no such thing as 'array context' in Perl, just
scalar context and list context. Arrays can can be called in either
context, but they themselves are not a context.
So really with the single scalar prototype it's just a list in scalar
context, which as I'm sure you know will just store and discard each
scalar to the left of a comma.
Notice that this is the same as your example:
perl -le ' sub wtf($) { $_[0] }; @a = wtf (qw(6 7 8)); print @a;'
So what's really happening is qw(6 7 8) is getting assigned to $_[0]
rather than @_, then the array, @a gets assigned the value of $_[0].
The fact that
wtf qw(6 7 8)
is equivalent to:
wtf (('6', '7', '8'))
On 18/07/2012 14:15, Nick wrote:
> Here's a little off-topic on-topicality to clutter the list up. Excuse me for
> answering my own question. I hadn't an answer when I started writing this (so it
> served my purpose at least), and I figure I may as well send this.
>
>
> What would you expect this to print?
>
> perl -le ' sub wtf($) { @_ }; @a = wtf qw(6 7 8); print @a;'
>
> 6 right?
>
> Nope.
>
>
>
> Let's see what Deparse says:
>
> perl -MO=Deparse -le ' sub wtf($) { @_ }; @a = wtf qw(6 7 8); print @a;'
>
> BEGIN { $/ = "\n"; $\ = "\n"; }
> sub wtf ($) {
> @_;
> }
> @a = wtf(('???', '???', '8'));
> print @a;
>
>
> WTF are those '???' things? Discarded constants I suppose?
>
>
> Anyway, seems that the reason for the surprise is that in this case (with a
> prototype):
>
> wtf qw(6 7 8)
>
> is equivalent to:
>
> wtf (('6', '7', '8'))
>
>
>
> A list (as opposed to an array) in scalar context evaluates the to *last*
> element (a bit of another gotcha I happened to already know about). See also:
>
> perl -le 'sub wtf { my @a = 6, 7, 8; @a }; print wtf;' # -> 6
>
>
> perl -le 'sub wtf { my $a = (6, 7, 8); $a }; print wtf;' # -> 8
>
> Note the (absense of) brackets.
>
>
>
> At least if you turn warnings on you will get a warning about "useless use of a
> constant".
>
>
>
> N
> _______________________________________________
> Edinburgh-pm mailing list
> Edinburgh-pm at pm.org
> http://mail.pm.org/mailman/listinfo/edinburgh-pm
More information about the Edinburgh-pm
mailing list