Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Perl store an array reference as a hash key?

Tags:

perl

Consider the following:

use strict;
use Data::Dumper;
my $hash={['one','two']=>[1,2]};
print Dumper($hash);
=for comment
prints....
$VAR1 = {
          'ARRAY(0x35358)' => [
                               1,
                               2
                              ]
         };
=cut

As an alternative, the key in the hash can be constrcuted as "one\ttwo" and then I can separate out the elements of the key based on tab delimiter (in latter part of the program while munging the data).

Any advice on how to store the key as a array reference?

like image 792
Sachin Avatar asked Dec 17 '22 23:12

Sachin


2 Answers

No, a normal (non-tied) Perl hash can only have strings as keys. Anything else - arrayrefs, objects, whatever - will be stringified if used as a hash key, which leaves the hash key unusable as whatever non-string thing you originally had.

Hash::MultiKey uses the magic of tie to sidestep this restriction.

like image 122
Dave Sherohman Avatar answered Jan 10 '23 19:01

Dave Sherohman


Hash::MultiKey

like image 42
daxim Avatar answered Jan 10 '23 17:01

daxim