2011-02-23 174 views
1

我有此腳本如何將哈希數組推送到哈希數組?

#!/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; 
} 

在那裏我試圖插入AoHc這也是一個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. 

任何想法如何做到這一點?

回答

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

我不太清楚所得到的數據結構是您的本意,但現在你有計劃的工作,並能看到最終的結構,你可以修改它來獲得你所需要的。

+0

感謝您教我良好的編碼習慣。 – 2011-02-23 11:12:36

+0

很抱歉,它並不是很霸道:-) Perl的數據結構起初可能令人望而生畏,但當你習慣時,它們非常靈活。蘭德爾·施瓦茨(幾個Perl書籍的作者)有一個很好的文章在這裏展示引用和間接引用的所有組合:http://www.stonehenge.com/merlyn/UnixReview/col68.html;並且http://perldoc.perl.org/perldsc.html(來自cmdline的'perldoc perldsc')還有更多信息。 – 2011-02-23 11:17:59

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

哈希值始終是標量,因此要將數組存儲在哈希中,需要存儲對數組的引用。嘗試使用以下行,將散列值解引用到數組。

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