Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pairs as hash keys

Tags:

list

hash

perl

Does anyone know how to make a hash with pairs of strings serving as keys in perl?

Something like...

{
    ($key1, $key2) => $value1;
    ($key1, $key3) => $value2;
    ($key2, $key3) => $value3;

etc....

like image 258
Zack Avatar asked Mar 08 '13 15:03

Zack


1 Answers

You can't have a pair of scalars as a hash key, but you can make a multilevel hash:

my %hash;
$hash{$key1}{$key2} = $value1;
$hash{$key1}{$key3} = $value2;
$hash{$key2}{$key3} = $value3;

If you want to define it all at once:

my %hash = ( $key1 => { $key2 => $value1, $key3 => $value2 },
             $key2 => { $key3 => $value3 } );

Alternatively, if it works for your situation, you could just concatenate your keys together

$hash{$key1 . $key2} = $value1;   # etc

Or add a delimiter to separate the keys:

$hash{"$key1:$key2"} = $value1;   # etc
like image 166
friedo Avatar answered Oct 11 '22 07:10

friedo