Fat comma

Fat comma (also termed hash rocket in Ruby and a fat arrow in JavaScript) refers to the "=>" operator present in some programming languages. It is primarily associated with PHP, Ruby and Perl programming languages, which use it to declare hashes. Using a fat comma to bind key-value pairs in a hash, instead of using a comma, is considered an example of good idiomatic Perl.[1] In CoffeeScript and TypeScript, the fat comma is used to declare a function that is bound to this.[2][3]

# a typical, idiomatic use of the fat comma in Perl
my %newHash = ( first_name => "Tom", last_name => "Auger" );

Subtleties

Perl

The "fat comma" forces the word to its left to be interpreted as a string.[4]

Thus, where this would produce a run-time error under strict (barewords are not allowed):

%badHash = ( bad_bareword, "not so cool" );

the following use of the fat comma would be legal and idiomatic:

%goodHash = ( converted_to_string => "very monkish" );

This is because the token converted_to_string would be converted to the string literal "converted_to_string" which is a legal argument in a hash key assignment. The result is easier-to-read code, with a stronger emphasis on the name-value pairing of associative arrays.

PHP

In PHP, the fat comma is termed a double arrow, and is used to specify key/value relationships when declaring an array. Unlike in Perl, the double arrow does not treat what comes before it as a bare word, but rather evaluates it. Hence, constants used with the double arrow will be evaluated:

$array = array( "name" => "PHP", "influences" => array( "Perl", "C", "C++", "Java", "Tcl" ) );

Ruby

In Ruby, the fat comma is the token to create hashes. Ruby 1.9 introduced a special syntax to use symbols as barewords.[5][6] In Ruby, the fat comma is called a hash rocket.[6]

# Old syntax
old_hash = { :name => 'Ruby', :influences => ['Perl', 'Python', 'Smalltalk'] }

# New syntax (Ruby >= 1.9)
new_hash = { name: 'Ruby', influences: ['Perl', 'Python', 'Smalltalk'] }

References

  1. Conway, Damian (2005). "4: Values and Expressions". In Allison Randal and Tatiana Appandi. Perl Best Practices. O'Reilly Media, Inc. p. 66. ISBN 0-596-00173-8. Whenever you are creating a list of key/value or name/value pairs, use the "fat comma" (=>) to connect the keys to their corresponding values.
  2. Ashkenas, Jeremy. "Coffeescript Documentation: grammar.coffee".
  3. http://www.typescriptlang.org/docs/handbook/functions.html
  4. perldoc.perl.org – perlop – Comma Operator
  5. Galero, Michael. "Ruby 1.9 Hash in Ruby 1.8". Retrieved 3 April 2008.
  6. 1 2 Nash, Phil. "I don't like the Ruby 1.9 hash syntax". Logical Friday. Retrieved 13 July 2011.
This article is issued from Wikipedia - version of the 10/30/2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.