问题描述
以下为何有效?
my @ys = map { $_ * $_ } @xs;
以下内容无效吗?
my @ys = map { $_ * $_ }, @xs;
map
是语言构造而不是真正的函数,还是块的特殊规则?
Is map
a language construct and not really a function, or are there special rules for blocks?
推荐答案
map
是列表运算符和核心函数.这是简单的Perl语法,在子程序的块参数之后不期望逗号. map
的特殊之处在于它也可以采用map EXPR, LIST
的形式.如果将其与标准子例程一起使用,则将仅对EXPR
进行评估并将其作为第一个参数传递.
map
is list operator and a core function. It is simple Perl syntax that expects no comma after a block parameter to a subroutine. The special thing about map
is that it can also take the form map EXPR, LIST
. If this was used with a standard subroutine the EXPR
would just be evaluated and passed as the first parameter.
块参数对所有子例程均有效,并且在将原型应用于子例程定义时可以使用.例如,您可以定义一个mymap
,其行为与编写时的行为相同
Block parameters are valid for all subroutines, and can be used if you apply prototypes to your subroutine definition. For instance, you could define a mymap
that behaved just the same way by writing
use strict;
use warnings;
use 5.010;
sub mymap(&@) {
use Data::Dump;
my $sub = shift;
my @newlist;
push @newlist, $sub->($_) for @_;
@newlist;
}
say for mymap { $_ * $_ } 1, 2, 3;
输出
1
4
9
但是一般来说,除非您确切地知道您在做什么,否则应该避免使用原型.通常,有一种更好的方式来编写代码.
But in general you should avoid prototypes unless you know exactly what you are doing. There is generally a better way to write your code.
这篇关于为什么要映射的参数之间不需要逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!