basics beginner
How to use the each function to iterate over hashes
Question
What is the best way to loop through all key-value pairs in a Perl hash?
Perl offers several ways to iterate over hashes, each with different use cases:
use strict;
use warnings;
my %hash = (
name => 'Alice',
age => 30,
city => 'NYC',
);
# Method 1: Using each (most efficient)
while (my ($key, $value) = each %hash) {
print "$key => $value\n";
}
# Method 2: Using keys (when you need sorted output)
for my $key (sort keys %hash) {
print "$key => $hash{$key}\n";
}
# Method 3: Using values (when you only need values)
for my $value (values %hash) {
print "Value: $value\n";
}
# Modern syntax with each (Perl 5.14+)
use v5.14;
while (my ($k, $v) = each %hash) {
say "$k => $v";
}
# Get all pairs at once
my @pairs = map { "$_ => $hash{$_}" } keys %hash;
# Hash slice
my @values = @hash{qw(name age)};
print "Name: $values[0], Age: $values[1]\n";
Use each for large hashes (memory efficient), keys when you need ordering, and values when you don't need keys.