Fat comma

From Infogalactic: the planetary knowledge core
Jump to: navigation, search

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, the fat comma is used to declare a function that is bound to this.[2]

# 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.[3]

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.[4][5] In Ruby, the fat comma is occasionally called a hash rocket.[5][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

<templatestyles src="Reflist/styles.css" />

Cite error: Invalid <references> tag; parameter "group" is allowed only.

Use <references />, or <references group="..." />

<templatestyles src="Asbox/styles.css"></templatestyles>

  1. Lua error in package.lua at line 80: module 'strict' not found.
  2. Lua error in package.lua at line 80: module 'strict' not found.
  3. perldoc.perl.org – perlop – Comma Operator
  4. Lua error in package.lua at line 80: module 'strict' not found.
  5. 5.0 5.1 Lua error in package.lua at line 80: module 'strict' not found.
  6. Lua error in package.lua at line 80: module 'strict' not found.