Perl:如何打印哈希数组,

Ken*_*ram 1 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";  
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到的错误消息:

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.
Run Code Online (Sandbox Code Playgroud)

我在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!'
        ];
Run Code Online (Sandbox Code Playgroud)

sim*_*que 6

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

push @holding, \%data;
Run Code Online (Sandbox Code Playgroud)

反斜杠\为您提供了一个参考%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!"
]
Run Code Online (Sandbox Code Playgroud)