Hashes 101: Mastering Key-Value Pairs

While arrays store ordered lists accessible by numeric index, Hashes allow you to store data as unordered key-value pairs. Think of a hash as a dictionary: you look up a word (the key) to find its definition (the value).

Hashes use the percent sigil (%) (think % for Pairs).

Declaring a Hash

In Perl, we associate keys and values using the "fat comma" operator (=>). The key is on the left, and the value is on the right:

use strict;
use warnings;

my %user_roles = (
    "admin"     => "Vax",
    "moderator" => "Alice",
    "guest"     => "Bob"
);

Accessing Hash Values

Because any single value fetched from a hash is a singular scalar, you access it using the scalar sigil ($) and wrap the key in curly braces ({}):

# Look up the admin name:
my $admin_user = $user_roles{"admin"};
print "The admin is $admin_user\n"; # Outputs: The admin is Vax

Adding or Modifying Elements

Manipulating entries is as simple as assigning directly to a specified key:

# Add a new user
$user_roles{"editor"} = "Charlie";

# Update an existing user
$user_roles{"guest"} = "Dave";
Next Module ->