0

为什么我从来没有见过这样的例子,你声明了哈希,然后把它放在另一个哈希中?

my %hash1={};
$hash1{'key1'}='1-111';
$hash1{'key2'}='1-222';
$hash1{'key3'}='1-333';
my %hash2={};
$hash2{'key1'}='2-111';
$hash2{'key2'}='2-222';
$hash2{'key3'}='2-333';

my %main_hash1={%hash1, %hash2};

我只见过这样的例子,他们将哈希放在哈希中,而不是哈希的变量:

my %main_hash2=( 'hash1' => {
                            'key1' => '1-111',
                            'key2' => '1-222',
                            'key3' => '1-333'
                    },
             'hash2' => {
                            'key1' => '2-111',
                            'key2' => '2-222',
                            'key3' => '2-333'
                    }
);

(也与数组类似)

4

2 回答 2

2

您不能将哈希存储在哈希中,但是可以将 hashref 存储在哈希中:

my %main_hash1 = ( hash1 => \%hash1, hash2 => \%hash2 );

数组也是如此:

my @main_array1 = ( \@array1, \@array2 );

并混合:

my @array_of_hrefs = ( \%hash1, \%hash2 );
my %hash_of_arefs = ( arr1 => \@arr1, arr2 => \@arr2 );

这是一直在做的;我不知道你为什么没有看到它,我怀疑 SO 上的任何人都会知道这个答案。

此外,这不会初始化哈希:

my %hash1={}; ## should be my %hash1; or my %hash1 = ();
于 2012-05-30T20:25:19.523 回答
0

请参阅以下示例:

Perl 代码:

my %hash1;
$hash1{'key1'}='1-111';
$hash1{'key2'}='1-222';
$hash1{'key3'}='1-333';

my %hash2;
$hash2{'key1'}='2-111';
$hash2{'key2'}='2-222';
$hash2{'key3'}='2-333';

my %main_hash = ( hash1 => \%hash1, hash2 => \%hash2 );
use Data::Dumper;
print Dumper %main_hash;

输出 :

$VAR1 = 'hash2';
$VAR2 = {
          'key2' => '2-222',
          'key1' => '2-111',
          'key3' => '2-333'
        };
$VAR3 = 'hash1';
$VAR4 = {
          'key2' => '1-222',
          'key1' => '1-111',
          'key3' => '1-333'
        };

使用参考,请参阅http://perldoc.perl.org/perlreftut.html和如果需要: http: //perldoc.perl.org/perlref.html

有一个 ref 技巧让事情变得有点神奇:

my $hash_ref = {}; # reference to a blank hash

my %h = ( foo => "1", bar => "2" );

push @{$hash_ref->{'1st_level'}->{'level-2'}->{'level_3'}->{'arr'}}, 123;
push @{$hash_ref->{'1st_level'}->{'level-2'}->{'level_3'}->{'arr'}}, 456;
$hash_ref->{'1st_level'}->{'level-2'}->{'level_3'}->{'arr'}->[2] = \%h;
use Data::Dumper;
print Dumper $hash_ref;

输出 :

$VAR1 = {
          '1st_level' => {
                           'level-2' => {
                                          'level_3' => {
                                                         'arr' => [
                                                                    123,
                                                                    456,
                                                                    {
                                                                      'bar' => '2',
                                                                      'foo' => '1'
                                                                    }
                                                                  ]
                                                       }
                                        }
                         }
        };
于 2012-05-30T20:25:32.357 回答