【问题标题】:map(encode_entities, @_) does not seem to workmap(encode_entities, @_) 似乎不起作用
【发布时间】:2018-08-29 18:03:51
【问题描述】:

map(encode_entities, @_) 似乎不起作用,函数来自HTML::Entities。我可以解决它(见下文),但有没有更丑陋的方法?有人可以解释发生了什么——我的想法是否存在概念错误?

use HTML::Entities;

sub foo {
    my @list = map(encode_entities, @_);
    return @list;
}

sub bar {
    my @list = @_;
    my $n = scalar @list;
    for my $k (0..$n-1) {
        $list[$k] = encode_entities($list[$k]);
    }
    return @list;
}

my @test = ('1 < 2', 'Hello world!');
print join("\n", bar(@test)); # prints the two lines, encoded as expected
print join("\n", foo(@test)); # undefined, gives "Use of uninitialized value..." error

【问题讨论】:

标签: perl cpan higher-order-functions


【解决方案1】:

没有理由假设除 Perl 运算符之外的任何东西都会使用 $_ 作为默认参数:必须仔细编写才能做到这一点

您需要做的就是使用特定参数调用encode_entities

试试这个

sub baz {
    map encode_entities($_), @_;
}

您可能会觉得没有必要单独定义子程序

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 1970-01-01
    • 2016-11-29
    • 2016-02-01
    • 2020-09-23
    • 2010-12-05
    • 2011-06-14
    • 2015-01-10
    • 2016-02-24
    相关资源
    最近更新 更多