Hash::MultiValue is an object (and a blessed hash reference) designed to handle cases where a single key may have multiple associated values, such as web request parameters. It allows you to treat the object like a standard hash for single-value access while providing an explicit API to retrieve all values for a key.
Key Behaviors
- Single Value Access: When accessing a key via
$hash->{key} or $hash->get($key), the last value entered for that key is returned. This mimics standard Perl behavior (e.g., merging hashes or taking a scalar from a list). - Multi-Value Access: Use
$hash->get_all($key) to retrieve all values associated with a key as a list. - Key Iteration:
keys %$hash returns only unique keys (standard hash behavior).$hash->keys returns all keys, including duplicates, in the order they were added.
Basic Usage
use Hash::MultiValue;
my $hash = Hash::MultiValue->new(
foo => 'a',
foo => 'b',
bar => 'baz',
);
my $foo = $hash->{foo}; # 'b' (the last entry)
my $foo = $hash->get('foo'); # 'b'
my @foo = $hash->get_all('foo'); # ('a', 'b')
keys %$hash; # ('foo', 'bar')
$hash->keys; # ('foo', 'foo', 'bar')