Hashes

Contents
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

Related articles
Perl
Perl course: zero to hero in 50 lessons
What is Perl and where it runs
Install Perl and check the version
Your first Perl script
The debugger as a REPL
Scalars and sigils
Numbers
Strings
Interpolation and quoting
Arrays
push, pop, shift and splice
Hashes
keys, values, exists and delete
Scalar and list context
Conditions and comparison
while, for, next and last
foreach and the default variable
Subroutines
Arguments in @_
References
Nested data structures
Regular expressions: match and anchors
Captures and named groups
Substitution with s///
split and join
grep and map
Sort and the Schwartzian transform
Read and write files
File tests and metadata
Directories and paths
die, warn and eval
Modules and Exporter
CPAN and cpanm
Objects with bless
Modern objects with Moo
Testing with Test::More
strict, warnings and diagnostics
Options with Getopt::Long
Environment and %ENV
system, backticks and pipes
One-liners with -n and -p
CSV and TSV processing
JSON with JSON::PP
HTTP clients with HTTP::Tiny
Sockets and IO::Socket
Databases with DBI
Capstone: todo CLI
Capstone: log report
Performance and profiling
Modern Perl tour
Hero roadmap: the whole course on one page
Install Perl on Windows 11
Install Perl on Ubuntu
Install Perl on Rocky Linux
Install Perl on macOS
Install Perl on FreeBSD
Perl in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: