【问题标题】:Perl: How to access an array thats inside of 3 hashes passed to subroutine by referencePerl:如何访问通过引用传递给子例程的 3 个哈希内的数组
【发布时间】:2017-07-18 21:22:09
【问题描述】:

我有一个类似这样的代码:

foreach $item (@total_data)
{
    setinfo($item);
} # @total_data contains an array of references to hashes (\%hash1 ... \%hashN)

在子程序中是这样的:

sub setinfo
{

    my ($argument) = @_;

    my $i = 0;


    #inside original hash $argument{"data"}{"fulldraw"} there is an [array]
    #that  contains numbers of the form XYYZ and I want to split them into
    #the following pairs XY YY YZ but that code works ok#

    foreach $item (${$argument{"data"}{"fulldraw"}})
    {
        my $match;
        my $matchedstr;

        if ($item =~ /^\d{4}$/) 
        { 

                          ...
        }
        else
        {
            print STDERR "DISCARDED: $item\n";
        }
    }


}

我知道我在取消引用时可能犯了一个错误,但我无法通过我在互联网上阅读的所有文章来弄清楚。

谢谢!

【问题讨论】:

标签: perl multidimensional-array hash dereference


【解决方案1】:

只需使用取消引用@{ ... }

foreach $item (@{ $argument->{data}{fulldraw} })

您可以使用Data::Dumper 来可视化复杂结构:

use Data::Dumper;
print Dumper($argument);

【讨论】:

  • 嗨,不行,它甚至不执行 foreach 循环。
  • 已修复。您访问的是哈希 %argument,而不是 $argument 引用的哈希。
【解决方案2】:
@{ ... } # dereference

也许 $argument 是一个 hashref;你需要使用

foreach $item (@{ $argument->{data}->{fulldraw} })

【讨论】:

  • 嗨,我还在尝试,几分钟前我想出了:foreach $item (@{$$argument{"data"}{"fulldraw"}}) 并且效果很好。你说的是一样的吗?
  • 它的工作原理相同。现在我还有一个问题可以问你。
  • @SJPRO 相同。 $argument 是 hashref,不是 hash,所以需要取消引用或者使用其他语法。
  • @SJPRO,$$argument{"data"}是一种可读性较差的写法$argument->{"data"},这是一种可读性较差的写法$argument->{data}
猜你喜欢
  • 2017-01-18
  • 2016-12-04
  • 2011-01-17
  • 2011-02-01
  • 2015-12-23
  • 1970-01-01
  • 2013-09-27
  • 2014-12-18
  • 2011-10-22
相关资源
最近更新 更多