Can Perl store an array reference as a hash key?

前端 未结 4 1800
野性不改
野性不改 2021-01-03 08:41

Consider the following:

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


        
相关标签:
4条回答
  • 2021-01-03 09:14

    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 讨论(0)
  • 2021-01-03 09:15

    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.

    0 讨论(0)
  • 2021-01-03 09:18

    Hash::MultiKey

    0 讨论(0)
  • 2021-01-03 09:20

    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.

    0 讨论(0)
提交回复
热议问题