Section 16.4. Unquoted Hash Keys


16.4. Unquoted Hash Keys

Perl offers many shortcuts that can help the programmer, such as omitting the quote marks on some hash keys.

You can't omit the quote marks on every key since a hash key may be any arbitrary string. But keys are often simple. If the hash key only consists of letters, digits, and underscores without starting with a digit, you may be able to omit the quote marks. This kind of simple string without quote marks is called a bareword since it stands alone without quotes.

One place you are permitted to use this shortcut is the most common place a hash key appears, which is in the curly braces of a hash element reference. For example, instead of $score{"fred"}, you could write $score{fred}. Since many hash keys are like this, not using quotes is a convenience. But beware: if there's anything inside the curly braces besides a bareword, Perl will interpret it as an expression.

Another place where hash keys appear is when assigning an entire hash using a list of key/value pairs. The big arrow (=>) is especially useful between a key and a value because (if the key is a bareword) the big arrow quotes it for you:

     # Hash containing bowling scores     my %score = (       barney   => 195,       fred     => 205,       dino     => 30,     ); 

This is the one important difference between the big arrow and a comma; a bareword to the left of the big arrow is implicitly quoted. (Whatever is on the right is left alone.) You don't have to use this feature of the big arrow only for hashes, though that's the most frequent use.



Learning Perl
Learning Perl, 5th Edition
ISBN: 0596520107
EAN: 2147483647
Year: 2003
Pages: 232

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net