Perl:如何打印哈希数组,

时间:2016-09-08 08:33:34

标签: perl perl-data-structures

似乎很多人使用包含哈希的数组。 我想检查我在sub中构建的数组,但是我在访问结构时遇到了一些问题。也许我并没有想象它的存在方式。这是一些代码的示例:

#!/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中使用数组的工作并不广泛,所以我确定我错过了一些基本的东西。

当我使用Dumper时,我期待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!'
        ];

2 个答案:

答案 0 :(得分:6)

您需要使用引用。如果将哈希值推送到数组中,它只是一个平面列表。您在循环中使用了正确的解除引用运算符,但在推送时却错过了反斜杠\

push @holding, \%data;

反斜杠\为您提供%data的引用,这是一个标量值。这将被推入你的阵列。

请参阅perlreftut以获取解释。

如果您在两次@holding次操作后查看push,那么很明显会发生什么。

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