tags:

views:

142

answers:

2

Is there way to implement a C++ multimap in perl?

+7  A: 

Use a hash of arrays.

my %students = ( # keys are IDs, values are enrollments
    100023 => [qw(Geography Mining)],
    100058 => [qw(Geography Geology Woodcraft)],
);
daxim
just to be precise, you really want a hash of array refs
frankc
+2  A: 

If by multimap you mean the C++ multimap, then the answer is yes. In Perl, a map corresponds to a hash. The value associated with a given key in the hash can be a reference to a hash. Perl also does not require you to use -> after the first indexing operation, so instead of saying $h{key1}->{key2} you can just say $h{key1}{key2} which gives you a convincing illusion of a multi-dimensional hash.

Here is an example:

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

my %h;

my $i;
for my $k (qw/one two three/) {
    for my $j (qw/a b c/) {
        $h{$k}{$j} = $i++;
    }
}

print "one b should be 1: $h{one}{b}\n",
    Dumper \%h;
Chas. Owens