Perl传递来自Foreach循环的子例程的哈希引用(哈希数组)

时间:2016-07-29 21:14:46

标签: perl hash perl-module subroutine

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

好的..这是我的代码,

@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)';

1 个答案:

答案 0 :(得分:5)

您对哈希和数组的引用感到困惑。

数组声明为:

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

哈希声明为:

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

那是因为哈希和数组都只是列表(花哨的列表,但我离题了)。您需要使用[]{}的唯一时间是您希望使用列表中包含的值,或者您想要创建任一列表的引用(更多信息如下)。

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

数组引用声明如下:

a

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

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

...引用被推送到my @array = [1, 2, 3]; 的第一个元素,这可能不是你想要的。

哈希引用声明如下:

@array

在数组(而不是aref)上使用my $href = {a => 1, b => 2}; 的唯一时间是您使用它来使用元素:[]。与哈希相似,除非它是引用,否则您只能使用$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;
}

我写了一篇关于Perl引用的教程,你可能对guide to Perl references感兴趣。还有perlreftut

最后一点......哈希在数组内部以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中结构的顶层可以包含多个值。下面的所有其他内容必须是单个标量值。因此,您可以拥有一个哈希数组,但从技术上和字面上看,它是一个包含标量的数组,其值是另一个结构的指针(引用)。指针/引用是单个值。

相关问题