[Edinburgh-pm] a Perl surprise

Jeff Parsons bynari at gmail.com
Wed Jul 18 11:26:33 PDT 2012

On 18/07/2012 18:32, Nick wrote:
> Yes indeed, another potential surprise.  I hadn't thought of it in terms of the
> "comma operator", and in fact I don't normally consider it an operator so much
> as a piece of delimiting syntax.  I'll try and remember to.
> I confess I don't find this particular behaviour of commas very useful in
> practise, and it has the side-effect of the surprising behaviour we're
> discussing.  I'm trying and failing to think of a case where it helps.  Can you
> think of one?

I personally can't think of a reason when comma operator in scalar 
context's behaviour is useful, but A) I'm sure there is and B) Perl is 
all about flexibility and freedom. It's what gives Perl its power but 
also makes it trickier than other languages like Python. Perl in terms 
of what you can do is the most powerful out of python/ruby/perl. There's 
things Perl can do that python/ruby can't like a program modifying its 
own op tree. It's Perl's flexibility and power that gives us coolness 
like Moose and MooseX::Declare or even perl5i, which I used to use, but 
decided not to now. perl5i is still extremely cool though. :-)

>>>    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
>> I don't think your first example there shows what you think it does —
>> the relative precedence of assignment and comma make it identical to
>> perl -le 'sub wtf { (my @a = 6), 7, 8; @a } print wtf'
> Actually, that is in fact what I understood it to mean.  This example was meant
> to show another case where the grammar rules are (in my opinion) surprising,
> even having learnt them.  When would I ever want to silently discard the terms 7
> and 8 like this? It seems more practical to either
>   a) have Perl "DWIM" (and assign the values to the list),
> or perhaps preferably,
>   b) generate a syntax error (so I can alter it to be less ambiguous).
> If I really wanted to have the terms 7 and 8 evaluated and the result discarded
> (perhaps with some side effect) I would probably use semi-colons, not commas.

the warnings pragma will warn you of this. :-)

You'd never do something like @foo = 6, 7, 8 though. It wouldn't be 
practical for Perl to try to work out every case of "weirdness" and 
report a syntax error, since it's not a definition, just weirdness. 
That's what warnings is for though, but warnings is also not just for 
syntax-weirdness like this, but to help spot bugs where you *think* a 
value has been filled when really it's not etc.

More information about the Edinburgh-pm mailing list