【发布时间】:2021-03-27 11:57:43
【问题描述】:
我编写了一个脚本,它将scalar 和hash 数据传递到子例程中。
在传递 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(没有引用)并在子例程中检索。
【问题讨论】:
-
1. hashref 没有问题(只能是首选) 2. 核心中有
List::Util::uniq(或旧版本中的List::MoreUtils::uniq) 3. 你真的需要原型吗? 4.发帖前先试一下:那个@{}下的%$h{$key}不对,需要$h->{$key} -
@zdim:感谢您的建议。我有
List::Util::uniq的依赖问题。请参阅this 帖子。指出第 4 点。 -
啊,好的。
uniq曾经在List::MoreUtils中——你能安装它吗? (当然,使用你自己的也没问题) -
@zdim:不可能:|这就是为什么我选择在我的代码中使用
uniq子例程。 -
我喜欢你的
uniq实现。尽管我不会将其命名为 uniq,因为它通常与常用的 List::Util 或 List::MoreUtils 模块中的那个相关联。另外,当您可以让grep...成为最后一行时,将返回的数组收集到@uniq的目的是什么。也许 perl 比 away 优化,我不知道,否则它会毫无目的地使用额外的 cpu 周期和内存。