【问题标题】:Pass scalar and hash to subroutine in Perl将标量和散列传递给 Perl 中的子例程
【发布时间】:2021-03-27 11:57:43
【问题描述】:

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

在传递 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 周期和内存。

标签: perl reference


【解决方案1】:

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

f(%hash)

结果

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

因此,您必须在内部重新创建哈希。传递引用是一种常见且便宜得多的替代方法。

【讨论】:

    猜你喜欢
    • 2013-08-12
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    相关资源
    最近更新 更多