Perl 将散列引用从 Foreach 循环(散列数组)传递给子例程

Perl pass hash reference to Subroutine from Foreach loop (Array of Hash)

这对你来说可能很简单,但我已经尝试了一个多小时。

好的..这是我的代码,

@collection = [
{
            'name' => 'Flo',
            'model' => '23423',
            'type' => 'Associate',
            'id' => '1-23928-2392',
            'age' => '23',
},
{
            'name' => 'Flo1',
            'model' => '23424',
            'type' => 'Associate2',
            'id' => '1-23928-23922',
            'age' => '25',
}];

foreach my $row (@collection) {
  $build_status = $self->build_config($row);
}

sub build_config {
    my $self = shift;
    my %collect_rows = @_;
    #my %collect_rows = shift;

    print Dumper %collect_rows; exit;
    exit;
}

其中 $row 实际上是一个哈希。但是当我打印它时......它给出如下输出(我正在使用 Dumper),

$VAR1 = 'HASH(0x20a1d68)';

您将引用与哈希和数组混淆了。

数组声明为:

my @array = (1, 2, 3);

哈希声明为:

my %hash = (1 => 2, 3 => 4);

那是因为散列和数组都是简单的列表(花哨的列表,但我离题了)。您唯一需要使用 []{} 的时候是您想要使用列表中包含的值,或者您想要创建任一列表的引用(详见下文)。

请注意,=> 只是一个特殊的(即粗的)逗号,它引用了左侧,所以尽管它们做同样的事情,但 %h = (a, 1) 会中断,%h = ("a", 1) 工作正常,%h = (a => 1) 也工作正常,因为 a 被引用。

数组 reference 声明如下:

my $aref = [1, 2, 3];

...请注意,您需要将数组引用放入标量中。如果您不这样做,请这样做:

my @array = [1, 2, 3];

...引用被推到 @array 的第一个元素上,这可能不是您想要的。

散列引用声明如下:

my $href = {a => 1, b => 2};

唯一一次在数组(不是 aref)上使用 [] 是当您使用它来使用元素时:$array[1];。与哈希类似,除非它是引用,否则您仅使用 {} 来获取键的值:$hash{a}.

现在,要解决您的问题,您可以继续使用具有以下更改的参考资料:

use warnings;
use strict;

use Data::Dumper;

# declare an array ref with a list of hrefs

my $collection = [
    {
        'name' => 'Flo',
        ...
    },
    {
        'name' => 'Flo1',
        ...
    }
];

# dereference $collection with the "circumfix" operator, @{}
# ...note that $row will always be an href (see bottom of post)

foreach my $row (@{ $collection }) {
    my $build_status = build_config($row);
    print Dumper $build_status;
}

sub build_config {
    # shift, as we're only accepting a single param...
    # the $row href

    my $collect_rows = shift;
    return $collect_rows;
}

...或将其更改为使用非参考:

my @collection = (
    {
        'name' => 'Flo',
        ...
    },
    {
        'name' => 'Flo1',
        ...
    }
);

foreach my $row (@collection) {
    my $build_status = build_config($row);

    # build_config() accepts a single href ($row)
    # and in this case, returns an href as well

    print Dumper $build_status;
}

sub build_config {
    # we've been passed in a single href ($row)

    my $row = shift;

    # return an href as a scalar

    return $row;
}

我写了一篇关于您可能感兴趣的 Perl 参考资料的教程 guide to Perl references. There's also perlreftut

最后一点...散列在数组内部用 {} 声明,因为它们确实是散列引用。对于多维数据,在 Perl 中只有顶层结构可以包含多个值。下面的所有其他内容都必须是单个标量值。因此,您可以拥有一个哈希数组,但从技术上和字面上看,它是一个包含标量的数组,其中它们的值是指向另一个结构的指针(引用)。 pointer/reference 是单个值。