[Edinburgh-pm] a Perl surprise

Aaron Crane perl at aaroncrane.co.uk
Thu Jul 19 04:06:24 PDT 2012

Nick <oinksocket at letterboxes.org> 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?

No, I can't.  I think the reason Perl 5 behaves this way is that it
misguidedly imports C's comma operator pretty much wholesale, then
tweaks it for Perl's notion of context.  In C, the comma operator
turns out to be helpful for things like the three-part `for` loop, so
that you can put multiple expressions in a slot that syntactically
accepts only one.  But Perl has do{} to help with that, and makes much
less use of three-part `for` anyway.

It's telling that things don't work this way in Perl 6, I think.

>>>   perl -le 'sub wtf { my @a = 6, 7, 8; @a }; print wtf;' # -> 6
>> 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?

Ah, right, I see what you mean.

And, yes, I agree: `my @a = 6,7,8` ought to do what it looks like it
does.  Larry agrees too, it turns out; Perl 6 adjusts the precedence
levels (and a whole lot of other things) to make that work.

Aaron Crane ** http://aaroncrane.co.uk/

More information about the Edinburgh-pm mailing list