perl - 将 Perl 的映射与自定义函数一起使用

标签 perl higher-order-functions

我有一个 Perl 脚本(跳过许多不相关的行)

use HTML::Entities;
my @keys = ('ID', 'first', 'last'); # data is not actually constant
my @encodedKeys = map(encode_entities, @keys);

运行没有错误。但是当我尝试访问数组中的值时,我得到了错误:

Use of uninitialized value $encodedKeys[0] in join or string at myfile.pl line 48.

如果我删除映射,代码可以正常工作——也就是说,变量不是空字符串或空字符串。我究竟做错了什么?有没有一种很好的惯用方法来做到这一点? (按顺序执行显然是微不足道的。)

最佳答案

encode_entities 函数默认不使用$_,所以你需要给它一个参数。将您的 map 语句更改为以下内容即可:

my @encodedKeys = map {encode_entities $_} @keys

关于perl - 将 Perl 的映射与自定义函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7070705/

相关文章:

Perl 循环遍历哈希会产生奇怪的值

正则表达式从字符串中提取 IP 和端口

javascript - 使用 boolean 值作为参数的高阶函数

scala - 高阶函数定义中的括号错误(Scala)

windows - 如何在 Windows 上调试 Perl XS 代码

regex - 如何在 Perl 中检查值是数字、字母还是字母数字?

php - 什么是 PHP 和 Perl 共享的良好的纯文本配置文件格式?

swift - 高阶函数 : "Cannot invoke ' map' with an argument list of type '((_) -> _)' "

functional-programming - OCaml中的fold_tree

javascript - 如何用包含 TypeScript 中较新对象的数组替换对象数组?