17.4. Unquoted Hash KeysPerl offers many shortcuts that can help the programmer. Here's a handy one: you may omit the quote marks on some hash keys. Of course, you can't omit the quote marks on just any key, since a hash key may be any arbitrary string. But keys are often simple. If the hash key is made up of nothing but 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: in the curly braces of a hash element reference. For example, instead of $score{"fred"}, you could write simply $score{fred}. Since many hash keys are simple like this, not using quotes is a real 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 (again, only 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, though.) This feature of the big arrow doesn't have to be used only for hashes, although that's the most frequent use. Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|