PBP: 047 Thin Commas

The PBP cautions us not to use commas to separate and sequence statements.  I think this is good advice most of the time.

Perl’s comma operator has two roles, one of which people forget about.

It can be used to sequence statements inside the same statement, and it can be used as a list separator.

The PBP suggests only using it as a list separator, and that if you need to run multiple statements in a single statement that is what the do {} block is for.  Make your single statement a do {} which contains your other statements, separated normally with semicolons.

Considering I hardly ever run into that case, I can agree with it.  I can’t think of the last time I needed to use do {} or to use a comma as anything but a list separator.

The time I might use it is in the C-Style for loop.  Everyone says to avoid it, but there are a few times and places I find it just the right answer, and will use it. There, the ability to have multiple initializers or incrementors is useful.  It’s a pretty special case, and I don’t run in to it often lately.

I really don’t understand the hate-on some people have for the three-parameter for.  But I came from C.

One Response to “PBP: 047 Thin Commas”

  1. Ed Avis says:

    The second use of comma is also called the “C-style comma operator”. Like you, I’d only ever want to use it inside a for (;;) loop, and even there it would not be too much hardship to use a do {} block instead.

    But although there are few times you want to use it, there are many places when it unexpectedly gets in the way, giving a C-style ‘this then that’ when what you intended was a two-element list. Here is one example which recently turned up on another Perl blog:


    Here some_sub()->[0, -1] is intended to pass a two-element anonymous list, but the C-style comma operator gets picked instead of the list comma.

    It would be an improvement to Perl, IMHO, if there were a warning on uses of the C-style comma operator, and one day it could be removed entirely, leaving comma as unambiguously a way to create lists.

Leave a Reply