如何将哈希数组推送到哈希数组?

时间:2011-02-23 09:58:53

标签: arrays perl hash

我有这个脚本

#!/usr/bin/perl

use warnings;
use strict;

use Data::Dumper;

my %acc = ();

&insert_a(\%acc, 11);
&insert_p(\%acc, 111);
print Dumper %acc;

sub insert_a() {

    my $acc_ref = shift;

    $acc_ref->{"$_[0]"} = {
    a => -1,
    b => -1,
    c => [ { }, ],
    }
}

sub insert_p() {

    my $acc_ref = shift;

    my @AoH = (
    {
        d => -1,
        e => -1,
    }
    );

    push $acc_ref->{"$_[0]"}{"c"}, @AoH;
}

我正在尝试将AoH插入到c AoH,但我正在

Type of arg 1 to push must be array (not hash element) at ./push.pl line 36, near "@AoH;"
Execution of ./push.pl aborted due to compilation errors.

任何想法如何做到这一点?

3 个答案:

答案 0 :(得分:2)

具体问题是你只能推送到一个数组,所以你首先需要取消引用数组,然后,因为它在一个更大的数据结构中,你想将它的值设置为一个引用。

#!/usr/bin/perl

use warnings;
use strict;

use Data::Dumper;

my %acc = ();

# don't use & to call subs; that overrides prototypes (among other things)
# which you won't need to worry about, because you shouldn't be using
# prototypes here; they're used for something else in Perl.
insert_a(\%acc, 11);
insert_p(\%acc, 111);
# use \%acc to print as a nice-looking hashref, all in one variable
print Dumper \%acc;

# don't use () here - that's a prototype, and they're used for other things.
sub insert_a {

    my $acc_ref = shift;

    $acc_ref->{"$_[0]"} = {
    a => -1,
    b => -1,
    c => [ { }, ],
    }
}

# same here
sub insert_p {

    my $acc_ref = shift;

    my @AoH = (
      {
        d => -1,
        e => -1,
      }
    );

    # You need to dereference the first array, and pass it a reference
    # as the second argument.
    push @{ $acc_ref->{"$_[0]"}{"c"} }, \@AoH;
}

我不太确定生成的数据结构是否符合您的意图,但是现在您可以使用该程序并查看生成的结构,您可以对其进行修改以获得所需的数据。

答案 1 :(得分:1)

好吧,

push @{$acc_ref->{"$_[0]"}->{"c"}}, @AoH;

或者您可以尝试$acc_ref->{"$_[0]"}->{"c"} = \@AoH;

你的剧本,

use strict;
use warnings
use Data::Dumper;

my %acc = ();

&insert_a(\%acc, 11);
&insert_p(\%acc, 111);
print Dumper %acc;

sub insert_a() {

    my $acc_ref = shift;

    $acc_ref->{"$_[0]"} = {
    a => -1,
    b => -1,
    c => [ { }, ],
    }
}

sub insert_p() {

    my $acc_ref = shift;

    my @AoH = (
    {
        d => -1,
        e => -1,
    }
    );

    push @{$acc_ref->{"$_[0]"}->{"c"}}, @AoH;
}

<强>输出:

$VAR1 = '11';
$VAR2 = {
          'c' => [
                   {}
                 ],
          'a' => -1,
          'b' => -1
        };
$VAR3 = '111';
$VAR4 = {
          'c' => [
                   {
                     'e' => -1,
                     'd' => -1
                   }
                 ]
        };

答案 2 :(得分:1)

哈希值始终是标量,因此要将数组存储在哈希中,您需要存储对数组的引用。尝试使用以下行,其中散列值将取消引用到数组。

push @{ $acc_ref->{$_[0]}->{'c'} }, @AoH;