【问题标题】:Perl: How to print array of hashes,Perl:如何打印哈希数组,
【发布时间】:2016-09-08 08:33:33
【问题描述】:

似乎没有很多人使用包含哈希的数组的例子。 我想检查我在 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!'
        ];

【问题讨论】:

    标签: perl perl-data-structures


    【解决方案1】:

    您需要使用参考资料。如果将散列推入数组,它只是一个平面列表。您在循环中使用了正确的取消引用运算符,但在推送时缺少反斜杠 \

    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!"
    ]
    

    【讨论】:

    • 啊。对。我误解了“\”。感谢您的洞察力。非常简单,非常基础,最重要。
    【解决方案2】:

    即使你得到了正确的数据结构,这段代码仍然无法工作:

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

    【讨论】:

      猜你喜欢
      • 2012-07-22
      • 1970-01-01
      • 2015-01-09
      • 2020-10-16
      • 2013-06-24
      • 1970-01-01
      • 2011-10-27
      • 2012-10-23
      • 2016-02-21
      相关资源
      最近更新 更多