tjwrona1992 tjwrona1992 - 7 months ago 25
Perl Question

Perl "reverse comma operator" (Example from the book Programming Perl, 4th Edition)

I'm reading "Programming Perl" and ran into a strange example that does not seem to make sense. The book describes how the comma operator in Perl will return only the last result when used in a scalar context.

Example:

# After this statement, $stuff = "three"
$stuff = ("one", "two", "three");


The book then gives this example of a "reverse comma operator" a few pages later (page 82)

# A "reverse comma operator".
return (pop(@foo), pop(@foo))[0];


However to me this doesn't seem to be reverse at all..?

Example:

# After this statement, $stuff = "three"
$stuff = reverse_comma("one", "two", "three");

# Implementation of the "reverse comma operator"
sub reverse_comma {
return (pop(@_), pop(@_))[0];
}


How is this in any way reverse of the normal comma operator? The results are the same, not reversed!

Here is a link to the exact page. The example is near the bottom.

Answer

It's a bad example, and should be forgotten.

What it's demonstrating is simple:

  • Normally, if you have a sequence of expressions separated by commas in scalar context, that can be interpreted an instance of the comma operator, which evaluates to the last thing in the sequence.

  • However, if you put that sequence in parentheses and stick [0] at the end, it turns that sequence into a list and takes its first element, e.g.

    my $x = (1, 2, 3)[0];
    

    For some reason, the book calls this the "reverse comma operator". This is a misnomer; it's just a list that's having its first element taken.

The book is confusing matters further by using the pop function twice in the arguments. These are evaluated from left to right, so the first pop evaluates to "three" and the second one to "two".

In any case: Don't ever use either the comma or "reverse comma" operators in real code. Both are likely to prove confusing to future readers.