Hashes

Learn about hashes, how to declare them, and how to index them in Perl.

A hash is an aggregate data structure that associates string keys with scalar values. Just as the name of a variable corresponds to something that holds a value, a hash key refers to something that contains a value. Think of a hash like a contact list: we use the names of our friends to look up their birthdays. Other languages call hashes tables, associative arrays, dictionaries, and maps.

Hashes have two important properties: they store one scalar per unique key and they provide no specific ordering of keys. Keep that latter property in mind. Though it has always been true in Perl, it’s very, very true in Modern Perl.

Declaring hashes

Hashes use the % sigil. We declare a lexical hash with this:

my %favorite_flavors;

A hash starts out empty. We could write my %favorite_flavors = ();, but that’s redundant.

Hashes use the scalar sigil $ when accessing individual elements and curly braces { } for keyed access:

Get hands-on with 1200+ tech skills courses.