BudiBadu Logo
Samplebadu

Perl by Example: Hashes

Perl 5

Storing key-value pairs with this sample code demonstrating hash declaration with % sigil, fat comma operator for initialization, element access with curly braces, hash iteration using each function, and keys/values extraction.

Code

#!/usr/bin/perl
use strict;
use warnings;

# Hashes start with %
my %colors = (
    "red"   => "#FF0000",
    "green" => "#00FF00",
    "blue"  => "#0000FF",
);

# Accessing values using $ and curly braces
print "Red hex: $colors{'red'}\n";

# Adding/Modifying elements
$colors{'white'} = "#FFFFFF";

# Iterating over a hash
while (my ($key, $value) = each %colors) {
    print "$key => $value\n";
}

# Getting keys and values
my @keys = keys %colors;
my @values = values %colors;

Explanation

Hashes, also known as associative arrays, are unordered collections of key-value pairs where each unique string key maps to a single scalar value. Hash variables are prefixed with the percent sign % sigil. The fat comma operator => separates keys from values during initialization and automatically quotes barewords on its left side, making hash literals more readable.

Hash element access uses the dollar sign $ sigil because accessing a single value returns a scalar, with keys specified in curly braces like $hash{'key'}. Keys must be unique strings, though Perl automatically converts other types to strings when used as keys. Values can be any scalar including numbers, strings, or references to complex data structures.

The each function iterates over hash key-value pairs, returning the next pair on each call until exhausted. The keys function returns a list of all keys, while values returns all values. The exists function checks key existence without autovivification, and delete removes key-value pairs. Hash order is not guaranteed and may vary between Perl versions, though Perl 5.18+ maintains insertion order in some contexts.

Code Breakdown

6
my %colors = (...) declares hash with % sigil for key-value pairs.
7
=> fat comma operator separates keys from values, auto-quotes left side.
13
$colors{'red'} accesses value using $ sigil, curly braces for hash lookup.
19
each %colors returns next key-value pair for iteration.