为什么Perl功能“映射”给出错误“地图的参数不足” [英] Why does Perl function "map" give the error "Not enough arguments for map"

查看:104
本文介绍了为什么Perl功能“映射”给出错误“地图的参数不足”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我不明白的东西。

此脚本正常工作(请注意地图中的拼接功能):

This script works correctly (notice the concatenation in the map functin):

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my %aa = map { 'a' . '' => 1 } (1..3);

print Dumper \%aa;

__END__
output:

$VAR1 = {
          'a' => 1
        };

但是没有并置,地图不起作用。这是我期望工作的脚本,但它不是:

But without concatenation the map does not work. Here is the script I expect to work, but it does not:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my %aa = map { 'a' => 1 } (1..3);

print Dumper \%aa;
__END__
output:

Not enough arguments for map at e.pl line 7, near "} ("
syntax error at e.pl line 7, near "} ("
Global symbol "%aa" requires explicit package name at e.pl line 9.
Execution of e.pl aborted due to compilation errors.

你能解释一下这种行为吗?

Can you please explain such behaviour?

推荐答案

Perl使用启发式方法来决定是否使用:

Perl uses heuristics to decide whether you're using:

map { STATEMENTS } LIST;   # or
map EXPR, LIST;

因为虽然{通常是块的开始,但也可能是开始一个hashref。

Because although "{" is often the start of a block, it might also be the start of a hashref.

这些启发式在令牌流(IIRC两个令牌)中看起来并不遥远。

These heuristics don't look ahead very far in the token stream (IIRC two tokens).

您可以使用以下方式强制{被解释为块:

You can force "{" to be interpreted as a block using:

map {; STATEMENTS } LIST;    # the semicolon acts as a disambigator

你可以强制{被解释为啊使用:

You can force "{" to be interpreted as a hash using:

map +{ LIST }, LIST;    # the plus sign acts as a disambigator

grep 同样受苦。 (技术上也是这样, do ,因为一个hashref可以作为一个参数给出,然后将其作为一个文件名进行字符串处理,这只是奇怪的。

grep suffers similarly. (Technically so does do, in that a hashref can be given as an argument, which will then be stringified and treated as if it were a filename. That's just weird though.)

这篇关于为什么Perl功能“映射”给出错误“地图的参数不足”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆