2016-09-08 132 views
0

似乎沒有很多使用包含散列的數組的人的例子。 我想檢查我在一個小組構造的數組,但我在訪問該結構時遇到了一些問題。也許我沒有想象它存在的方式。這是一些代碼示例:Perl:如何打印散列數組,

#!/usr/bin/perl 

use strict; 
use warnings; 
use Data::Dumper; 


my (%data, %data2, @holding); 

%data = (
    'monday' => "This stuff!", 
    'tuesday' => "That stuff!!", 
    'wed' => "Some other stuff!!!" 
    ); 

push @holding, %data; 

%data2 = (
    'monday' => "Yet more stuff... :-P ", 
    'tuesday' => "Some totally different stuff!", 
    'wed' => "What stuff is this?" 
    ); 

push @holding, %data2; 

foreach my $rows(@holding){ 
    foreach my $stuff (keys %{$holding[$rows]}){ 
     print "$holding[$rows]{$stuff}\n"; 
    } 
} 

錯誤消息我得到:

Argument "wed" isn't numeric in array element at /home/kingram/bin/test line 27. 
Can't use string ("wed") as a HASH ref while "strict refs" in use at /home/kingram/bin/test line 27. 

我在Perl中使用數組並不廣泛,所以我敢肯定,我失去了一些東西基本。

當我用自卸車我期待VAR1和VAR2表達兩個不同行,但我得到

$ ~/bin/test 
$VAR1 = [ 
      'wed', 
      'Some other stuff!!!', 
      'monday', 
      'This stuff!', 
      'tuesday', 
      'That stuff!!', 
      'wed', 
      'What stuff is this?', 
      'monday', 
      'Yet more stuff... :-P ', 
      'tuesday', 
      'Some totally different stuff!' 
     ]; 

回答

5

您需要引用工作。如果你將一個散列推入一個數組,它只是一個平坦的列表。您在循環中使用正確的解除引用操作符,但推送時缺少反斜槓\

push @holding, \%data; 

反斜線\給你一個參考%data,這是一個標量值。這將被推入你的數組中。

有關說明,請參閱perlreftut


如果你的兩個push手術後看@holding,很明顯會發生什麼。

use Data::Printer; 
p @holding; 

__END__ 
[ 
    [0] "monday", 
    [1] "This stuff!", 
    [2] "tuesday", 
    [3] "That stuff!!", 
    [4] "wed", 
    [5] "Some other stuff!!!", 
    [6] "wed", 
    [7] "What stuff is this?", 
    [8] "monday", 
    [9] "Yet more stuff... :-P ", 
    [10] "tuesday", 
    [11] "Some totally different stuff!" 
] 
+1

啊。對。我誤解了「\」。 感謝您的洞察力。非常簡單,非常基本,最重要。 –

1

即使你得到的數據結構正確,這個代碼仍然行不通:

foreach my $rows(@holding){ 
    foreach my $stuff (keys %{$holding[$rows]}){ 
     print "$holding[$rows]{$stuff}\n"; 
    } 
} 

當您使用foreach my $rows (@holding)每次迭代的陣列,一輪循環$rows將包含來自陣列的元素,而不是元素的索引。所以你不需要用$holding[$rows]來查找它。你的代碼應該看起來像這樣:

foreach my $rows (@holding){ 
    foreach my $stuff (keys %{$rows}){ 
     # $rows will contain a hash *reference*. 
     # Therefore use -> to access values. 
     print "$rows->{$stuff}\n"; 
    } 
}