perl散列哈希或数组数组的例子

时间:2012-05-30 20:12:30

标签: arrays perl hash

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

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'
                    }
);

(与数组类似)

2 个答案:

答案 0 :(得分: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 = ();

答案 1 :(得分: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

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

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'
                                                                    }
                                                                  ]
                                                       }
                                        }
                         }
        };