开发者

Can Perl store an array reference as a hash key?

Consider the following:

use strict;
use Data::Dumper;
my $hash={['one','two']=>[开发者_C百科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?


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.


Hash::MultiKey


What is the need here? Why would you be looking up a hash element by an array? It seems a case for a HoH, like:

use strict;
use warnings;
use Data::Dumper;
my $hash = { one => { two => [1,2] } };
print Dumper($hash);

prints

$VAR1 = {
          'one' => {
                     'two' => [
                                1,
                                2
                              ]
                   }
        };

especially since you will be splitting the array back into its elements later. To check for existence something like:

if (exists($hash->{one}) && exists($hash->{one}{two}))

the && is needed as

if (exists($hash->{one}{two}))

would autovivify $hash->{one} if it didn't exist.


You can serialize the data structure (e.g. with Data::Dumper or other similar tool) and use the string as a hash key:

my $hash = {
    Dumper(['one','two']) => [1,2],
};

Eval the key to get the data structure back.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜