Hashes
| Declaring a hash | |
| Read and write | |
| The fat comma | |
| Autovivification |
Declaring a hash
A hash is an unordered collection of key-value pairs, marked by the percent sign. Keys are strings, values are scalars, and the whole list sits in parentheses as key-value, key-value.
my %user = (
"name" => "Ada",
"age" => 36,
"city" => "London",
);
print "$user{name}\n"; # Ada
perl demo.pl
Ada
Order is not preserved and not promised. If you print the hash directly you get the pairs in whatever order the internal table happens to have, so sort the keys whenever output must be stable.
Read and write
One key is one scalar, so the sigil is a dollar sign. Writing to a key adds it or replaces the old value, and there is no separate update call.
my %user = ("name" => "Ada", "age" => 36, "city" => "London");
$user{age} = 37;
$user{role} = "admin";
print "$user{role}\n"; # admin
perl demo.pl
admin
Reading a key that was never written returns undef, and under use warnings you get a warning if you then use it as a string. Check with exists, which lesson 12 covers, before you trust a key.
The fat comma
=> is called the fat comma. It does exactly what a comma does, but it also quotes a bare word on its left, which is why hash literals read like a table instead of a string list.
my %limits = (
cpu => 80,
mem => 90,
disk => 95,
);
print $limits{disk}, "\n"; # 95
perl demo.pl
95
Keys with spaces or punctuation still need quotes, because the bare word rule only covers simple identifiers. Keep keys short and lower case and the literals stay readable.
Autovivification
Reading a missing key in a nested structure can create it, a behavior called autovivification. Counting with ++ relies on it: the key springs into existence with the value 1.
my %hits = ();
$hits{'/index.html'}++;
$hits{'/index.html'}++;
print $hits{'/index.html'}, "\n"; # 2
perl demo.pl
2
The same feature bites in conditions: if ($user{prefs}{theme}) happily creates an empty prefs hash just to look inside it. Use exists on each level when a missing branch must stay missing.
Next: keys, values, exists and delete
Article author: Arthur Isaev