How to create a hash from two arrays in Perl?
Question
How to create a hash from two arrays in Perl?
Creating a Hash from Two Arrays in Perl
In Perl, creating a hash from two arrays—where one array holds keys and the other holds corresponding values—is a common task when you want to map one set of data to another. Perl’s flexible nature makes this straightforward, but it’s important to handle the arrays carefully, especially if their lengths differ.
Basic Concept
You want to convert two arrays like:
my @keys = ('apple', 'banana', 'cherry');
my @values = (3, 7, 2);
into a hash:
%hash = (
'apple' => 3,
'banana' => 7,
'cherry' => 2,
);
How to Do This in Perl
Perl’s sigils are important to understand here:
@sigil indicates an array context%sigil indicates a hash$sigil indicates a scalar
The easiest way to build a hash from two arrays is by using map or the hash slice assignment, but the most natural is to create an array that alternates keys and values, then assign that list to a hash.
Example Using map and Indexing
use strict;
use warnings;
my @keys = ('apple', 'banana', 'cherry');
my @values = (3, 7, 2);
# Ensure both arrays are the same length (otherwise you might lose data or get undef)
my $length = @keys < @values ? @keys : @values;
# Map keys and values into a hash using slice indexes
my %hash = map { $keys[$_] => $values[$_] } 0 .. $length - 1;
# Print the hash to verify
while (my ($k, $v) = each %hash) {
print "$k => $v\n";
}
Explanation
- The
mapfunction iterates over the index range0 .. $length - 1. - For each index, it builds a key-value pair
$keys[$_] => $values[$_]. - Assigning the list output of
mapto a hash%hashautomatically pairs keys and values. - We perform length checking to avoid mismatches if one array is shorter.
Alternative: Using Hash Slice
Perl 5.14+ supports hash slices, so you can do this in one line:
my %hash;
@hash{@keys[0..$length-1]} = @values[0..$length-1];
This assigns values via slice notation, which is concise but slightly less obvious.
Common Pitfalls
- Unequal array lengths: If
@keysand@valuesdiffer in size, Perl silently assignsundefto missing values or ignores extra keys. Always check or normalize the arrays first. - Duplicate keys: Any duplicate keys in
@keyswill be overwritten in the hash, since keys must be unique. - Context matters: Assigning a list of pairs to a hash expects an even list of elements (key-value pairs). If the list length is odd, the last value is ignored and a warning may be issued with
use warnings;
Summary
To create a hash from two arrays in Perl, zip them by index to form key-value pairs, then assign that list to a hash. map and hash slices are idiomatic ways to do this, but always ensure keys and values arrays are aligned lengthwise to avoid unexpected behavior.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 5ms
(empty)(empty)