如何将数组哈希值传递给子程序?

时间:2013-03-22 02:22:50

标签: arrays perl hash reference subroutine

我有一个数组哈希。我正在尝试执行以下操作:因为我循环遍历哈希的键,我想将哈希值(在本例中为数组)传递给子例程。

一旦我进入子程序,我想对数组进行一系列计算,包括取数组中数值的平均值。最后根据计算返回一个值。

这是我所拥有的最小代表:

#!/usr/bin/perl
use warnings; use strict;
use List::Util qw(sum);

%data_set = (
    'node1' => ['1', '4', '5', '2'],
    'node2' => ['3', '2', '4', '12'],
    'node3' => ['5', '2', '3', '6'],
    );

foreach my $key ( keys %data_set ) {
    foreach ( @{$data_set{$key}} ) {
        my @array = split;   # it's not letting me 
        calculate(\@array);   ### I'm getting the error here!!
    }
}

sub calculate{
    my @array = @{$_};
    my $average = mean(\@array);
    # do some more calculations
    return; # return something
}

# sum returns the summation of all elements in the array
# dividing by @_ (which in scalar content gives the # of elements) returns
# the average
sub mean{
    return sum(@_)/@_;
}

快速说明:在第一次迭代node1中,我想将数组'1', '4', '5', '2'传递给子例程。

我认为,就我的目的而言,这可能比将数组哈希的引用传递给每个子例程更有效。你们有什么感想?无论如何,你们可以帮我解决这个问题吗?任何建议表示赞赏。感谢

2 个答案:

答案 0 :(得分:3)

我认为您在需要引用和取消引用变量以及传递的内容时会有点困惑。

让我们仔细看看,

foreach my $key ( keys %data_set ) {
    foreach ( @{$data_set{$key}} ) {
        my @array = split;   # it's not letting me 
        calculate(\@array);   ### I'm getting the error here!!
    }
}

循环遍历哈希以获取密钥,但随后您使用它们来访问值以取消引用数组并将每个数组拆分为单个元素数组(字符串)。然后将对该1元素数组的引用传递给calculate。基本上,如果您想要做的唯一事情是将散列(数组)的每个值传递到calculate子例程,那么您正在做太多工作。尝试这样的事情:

foreach my $key (keys %data_set){
    calculate($data_set{$key}); # This is already a reference to an array
}

此外,在calculate中,您需要将my @array = @{$_};更改为my @array = @{$_[0]};my @array = @{(shift)};

答案 1 :(得分:1)

您的平均子程序应如下所示:

sub mean{
    my @array = @{(shift)};
    return sum(@array)/scalar(@array);
}
相关问题