PBP: 046 Fat Commas

Perl has a weird but cool operator, the “fat comma”, written as =>.  It’s a comma, but with a special property that means a bareword on the left side is allowed.  They’re often used for initializing hashes without having to quote every hash key.

The PBP suggests reserving => for items that go together, or, as it says “for pairs”.  Name => value pairs, mostly.  These things are related to each other and => makes that visible. 

I agree with this, and almost always only use => for hash initialization or for named parameters to functions, which wind up being a hash anyway.

There are a bunch of other places they can be used – anywhere a comma can be! – but it’s really not a great idea.  Mr. Conway’s examples of “why this is ugly” are clear and I won’t repeat them.  (I am NOT trying to recapitulate his entire book!  Go get a copy, already!)

One common usage pattern he hasn’t mentioned, because it didn’t exist, is with Moose.  Creating accessors is often done with a fat comma:


has color => (

is => 'ro',

isa => 'Str',

required => 1,

);

This means you don’t have to (but many do anyway) quote the accessor name.  It really is a function call:


has('color', 'is', 'ro', 'isa', 'Str', 'required', 1);

Those two are equivalent.  (Yes they are!  has is the subroutine name, then the first parameter is a string.  The rest of the parameters are passed in the program as an array, but that gets flattened to all the items in the array, and the fat commas are just ordinary commas, so it’s just the attribute name, then alternating names and values.  Parsing name/value pairs like this coming into the function is pretty easy, so seeing it used this way isn’t too odd.  The hard part is making sure ‘has’ is set up right so it’ll always be callable without parenthesis.  I’m not sure if Moose prototyped it or not.)

Which is easier to read?  I’ll pick the fat commas every time.

 

One Response to “PBP: 046 Fat Commas”

  1. Andrew says:

    No prototype needed. As long as a sub has been declared or imported, it can be called list-style. That means that as long as the name isn’t immediately followed by parentheses, it will gobble up as many arguments to the right as the parser allows. Until the end of the statement or the end of surrounding parentheses, more or less.

Leave a Reply to Andrew