Monks
Further to my ramblings here about creating a hash that has multiple values per key I have gone the whole hog and written an object to perform this function having been advised that no such object currently exists. I don't think that it is comprehensive enough to be placed on CPAN but I do think that it may be useful to other users so I am posting it here.
Example usage and other details are included in the pod docs at the top of the file. Any constructive suggestions greatly appreciated. Code below:
=head1 NAME
Datastruct::MultiMap
=head1 DESCRIPTION
This object provides a simple front to a hash mapping keys to arrays o
+f
values thus allowing multiple values for a single key.
=head1 AUTHOR
Arun Horne (arun@simbios.net)
=head1 VERSION HISTORY
1.0 - Initial version (27 May 2003)
=head1 USAGE
use strict;
use warnings;
use Datastruct::MultiMap;
use Data::Dumper;
# Create a multimap object
my $map = Datastruct::MultiMap->new();
# Add some keys
$map->put('K1','V1');
$map->put('K1','V2');
$map->put('K2','V3');
$map->put('K3','V4');
print Dumper $map;
# Get values
my @values = $map->get('K1');
print Dumper \@values;
# Remove keys
$map->remove('K1');
print Dumper $map;
# Can still access as a normal hash if you want
print join(",", sort keys %$map), "\n";
=cut
package Datastruct::MultiMap;
use strict;
use warnings;
#
# Creates an empty multimap.
#
sub new()
{
my $class = shift;
my $self = {};
bless $self, $class;
return $self;
}
#
# Stores a (key, value) pair into the map
#
sub put()
{
my ($self, $key, $value) = @_;
unless (exists $self->{$key})
{
$self->{$key} = [];
}
push @{$self->{$key}}, $value;
}
#
# Returns an array of all the values mapped by the specific key
#
sub get()
{
my ($self, $key) = @_;
return @{$self->{$key}};
}
#
# Removes all of the values mapped by the specified key.
#
sub remove()
{
my ($self, $key) = @_;
delete $self->{$key};
}
# Package must return true
1;
____________
Arun