perl - 将标量和散列传递给 Perl 中的子例程
问题描述
我编写了一个脚本,它将 ascalar
和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
(没有参考)并在子程序中检索。
解决方案
您不能将散列(或数组)传递给 subs,只能传递零个或多个标量。使用
f(%hash)
结果是
f($key1, $hash{$key1}, $key2, $hash{$key2}, ...)
因此,您必须在内部重新创建哈希。传递参考是一种常见且便宜得多的选择。
推荐阅读
- python - Python Post 请求响应 Xml 错误加载 fromstring
- math - 将矩形分成n等份
- java - 使用 Jackson 序列化并在该字段上添加注释时,如何完全忽略字段的值?
- amazon-web-services - 如何在没有 OAI 的情况下使公共存储桶只能从云端访问?
- c - 从不断更新的日志文件中读取数据
- python - 如何删除 Pandas DataFrame 行中长度为 3 或更大的重复?
- reactjs - 如何使用 React 和 Redux 重置密码?
- c# - 使用 Microsoft Graphs SDK 向 Teams 用户发起呼叫
- javascript - 反应本机中的无效挂钩调用问题
- java - Java 指定文件中单个单词位置的最佳方法