[Edinburgh-pm] a Perl surprise

Nick oinksocket at letterboxes.org
Wed Jul 18 06:15:21 PDT 2012


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


More information about the Edinburgh-pm mailing list