One of the simplest but most useful examples of TIMTOWTDI in the design of
Perl is the fat comma operator (
=>), which acts like a regular
comma except that it automatically quotes barewords used as its left operands.
It also looks like an arrow, so it leads from left to right and implies a
stronger association between its operands than the normal comma does.
You can see this in hash initializers:
my %dogs = ( alpha => 'Rodney', clown => 'Lucky', puppy => 'Rosie', );
... which makes the association of key with value clearer than the standard comma does:
my %dogs = ( 'alpha', 'Rodney', 'clown', 'Lucky', 'puppy', 'Rosie', );
... and much clearer than even an idomatic bare list initializer might:
my %dogs = qw( alpha Rodney clown Lucky puppy Rosie );
You can use the fat comma in place of the normal comma almost anywhere its autoquoting semantics don't change your code. (I can't think of any at the moment, but there might be a JAPH somewhere that proves me wrong in a strange and wonderful away.) With Moose and other semi-keyword libraries using lots of named parameters, you often see code like:
has 'name' => ( is => 'rw', isa => 'Str' ); has 'age' => ( is => 'rw', isa => 'Int' );
There's nothing wrong with that code, but I confess that it confuses me a
little bit every time I skim it. I understand the desire to emphasize the name
of the attribute (
age) and to suggest that
all of the other parameters provided to
has are merely refinements
of the behavior of the attribute, such that grouping them by the parentheses
makes them into a single visual unit associated with the attribute's name, but
I never quite seem to read it that way.
(The lack of autoquoting in this example bothers me too.)
I started to think about this when I read some production code I'd written:
return $self->collaborative_collection( Name => $identifier );
The arguments to
collaborative_collection() are the name of the
collection and a unique identifier for the collaborative making the request.
There's no logical connection between the name and the identifier. I only used
the fat arrow for its autoquoting behavior.
The API call looked as if I were passing a single keyword argument, which isn't the case at all. I was passing two distinct arguments.
The temptation to use less punctuation (removing quotes) by using a little more punctuation (a fatter comma) had let me write code that would mislead other readers. If Perl had a different syntax for keyword arguments, I wouldn't have had this problem, but that's not going to fix this code here and now.
After some reflection, I decided that the association that the visual appearance of the fat comma implies is important enough to the reading of code that we should only use it where that relationship is present in the semantics of the code. Sure, it's a little extra punctuation that we don't have to type, but it's clearer code when we read it, and that's more important after all.