[Edinburgh-pm] a Perl surprise
Jeff Parsons
bynari at gmail.com
Wed Jul 18 06:40:17 PDT 2012
Uhhh, whoops, I hit send accidentally too early!
I was saying..
You said:
wtf qw(6 7 8)
is equivalent to:
wtf (('6', '7', '8'))
That's actually incorrect and wouldn't be important anyway. '6' is 6 as
a string, 6 is 6 as a number, they're not strictly the same thing.
They're not stored the same internally and perl certainly won't just
convert 6 to '6' unless you try to use 6 as a string.
The simple answer as to why what happens happens is internally, by
prototyping with a scalar you're just causing a
$_[0] = qw(6 7 8) to happen.
Hope I was clear in my explanation!
Regards,
Geoff
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