Perl Hashes
Hashes (also called associative arrays) are unordered collections of key-value pairs. They are prefixed with a % symbol and provide fast lookup by key.
Creating Hashes
# Simple hash creation
%person = (
"name" => "John Doe",
"age" => 30,
"occupation" => "Programmer"
);
# Using the fat comma (=>) which auto-quotes left side
%colors = (
red => "#FF0000",
green => "#00FF00",
blue => "#0000FF"
);
# From arrays (even number of elements)
@pairs = ("key1", "value1", "key2", "value2");
%hash = @pairs;
# Empty hash
%empty = ();
Accessing Hash Elements
# Accessing elements
print $person{"name"}; # "John Doe"
print $colors{"red"}; # "#FF0000"
# Checking existence
if (exists $person{"age"}) {
print "Age exists\n";
}
# Deleting elements
delete $person{"occupation"};
Hash Operations
# Getting all keys
@keys = keys %person; # ("name", "age", "occupation")
# Getting all values
@values = values %person;
# Iterating through hash
while (($key, $value) = each %person) {
print "$key => $value\n";
}
# Hash size
$size = keys %person; # Number of key-value pairs
# Clearing a hash
%person = (); # Empty the hash
undef %person; # Alternative way
Hash Slices
# Accessing multiple values
@values = @person{"name", "age"}; # ("John Doe", 30)
# Setting multiple values
@person{"name", "age"} = ("Jane Doe", 32);
Special Hash Variables
# Environment variables
print $ENV{"PATH"};
# Command line switches
use Getopt::Long;
GetOptions(\%options, "help", "verbose");
# Signal handlers
$SIG{"INT"} = \&handle_interrupt;
# Special hashes
%INC; # Hash of loaded modules
%ENV; # Environment variables
%SIG; # Signal handlers
Hash Functions
# Sorting keys
foreach $key (sort keys %hash) {
print "$key: $hash{$key}\n";
}
# Sorting by value
foreach $key (sort { $hash{$a} <=> $hash{$b} } keys %hash) {
print "$key: $hash{$key}\n";
}
# Merging hashes
%combined = (%hash1, %hash2); # Later values overwrite earlier
# Filtering
%filtered = map { $_ => $hash{$_} } grep { condition } keys %hash;
Multidimensional Hashes
# Hash of hashes
%employees = (
"1001" => {
name => "John Doe",
age => 30,
dept => "IT"
},
"1002" => {
name => "Jane Smith",
age => 28,
dept => "HR"
}
);
# Accessing elements
print $employees{"1001"}{"name"}; # "John Doe"
# Adding new record
$employees{"1003"} = {
name => "Bob Johnson",
age => 35,
dept => "Finance"
};
Best Practices
- Use meaningful keys that describe the data
- Check for key existence with
exists
before accessing - Consider using
each
for large hash iteration - Use hash slices for multiple value access
- Free memory with
undef
when done with large hashes