使用带有自定义函数的 Perl 映射
我有一个 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.
如果删除映射,代码将正常工作——也就是说,变量不是 null 或空字符串。我做错了什么?有一个很好的惯用方法来做到这一点吗? (按顺序进行显然是微不足道的。)
I have a Perl script that has (skipping many irrelevant lines)
use HTML::Entities;
my @keys = ('ID', 'first', 'last'); # data is not actually constant
my @encodedKeys = map(encode_entities, @keys);
which runs without error. But when I try to access the values in the array, I get errors:
Use of uninitialized value $encodedKeys[0] in join or string at myfile.pl line 48.
If I remove the mapping the code works properly -- that is, the variables are not null or empty strings. What am I doing wrong? Is there a good idiomatic way to do this? (It's obviously trivial to do sequentially.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
encode_entities
函数默认不使用$_
,因此您需要向其传递一个参数。将map
语句更改为以下内容即可:The
encode_entities
function does not use$_
by default, so you need to pass it an argument. Changing yourmap
statement to the following will work:为了使代码按照问题中发布的方式正常工作,需要对
encode_entities
进行原型设计。快速浏览一下源代码事实证明事实并非如此。正确的调用方法是:
For the code to work correctly as posted in the question,
encode_entities
needs to be prototyped. A quick glance at the source code shows that this isn't the case.The correct way to call it is:
由于
encode_entities
替换了 HTML 实体就地,您可能需要在@keys
的副本上使用map
:否则,
foreach
更适合该任务:Since
encode_entities
replaces HTML entities in-place, you may want to usemap
on a copy of@keys
:Otherwise,
foreach
is better suited for the task: