Can Perl store an array reference as a hash key?

前端 未结 4 1802
野性不改
野性不改 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: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.

提交回复
热议问题