首页 > 解决方案 > 将标量和散列传递给 Perl 中的子例程

问题描述

我编写了一个脚本,它将 ascalarhash数据传递到子例程中。

在传递一个时,hash我传递了一个引用,并在子例程中在迭代时取消引用它(使用foreach循环)。

#!/usr/bin/perl
use strict; use warnings;
use Data::Dumper;

my %hash = (
                '1' => [ 'A', 'B', 'Z', 'A' ],
                '2' => [ 'C', 'D' ],
                '3' => [ 'E', 'E' ]
);

my $keyword = "my_test_keyword";
print_data($keyword, \%hash);
print "End of the Program\n";

sub uniq (@) {
    my %seen;
    my $undef;
    my @uniq = grep defined($_) ? !$seen{$_}++ : !$undef++, @_;
    @uniq;
}

sub print_data {
    my ($kw, $h) = @_;
    print "Keyword:$kw\n"; #my_test_keyword should be printed
    
    foreach my $key (sort keys %$h) {
        print "Key:$key\n";
        print "Value(s):", join('#', uniq @{%$h{$key}}), "\n";
    }
    return;
}

这是一个好方法还是我需要按原样传递hash(没有参考)并在子程序中检索。

标签: perlreference

解决方案


您不能将散列(或数组)传递给 subs,只能传递零个或多个标量。使用

f(%hash)

结果是

f($key1, $hash{$key1}, $key2, $hash{$key2}, ...)

因此,您必须在内部重新创建哈希。传递参考是一种常见且便宜得多的选择。


推荐阅读