和map相关的一个问题

和map相关的一个问题

刚开始看<<Intermediate Perl>>
在练习的时候遇到一个问题,两段语义相近的代码,一个能正常运行,一个报语法错误,
不知哪里出错了。
@array = qw(This is Hello World);
$blank = " ";
@result = map {$blank,$_,"\n"} @array;
print @result;

运行结果为:
This
is
Hello
World
@array = qw(This is Hello World);
@result = map {" ",$_,"\n"} @array;
print @result;

编译错误:
Not enough arguments for map at test.pl line 2, near "} @array"
syntax error at test.pl line 3, near "} @array"
Execution of test.pl aborted due to compilation errors.

PS: Perl 版本为v5.10.0 Windows平台



QUOTE:
原帖由 _Erics 于 2008-12-9 23:41 发表
刚开始看
在练习的时候遇到一个问题,两段语义相近的代码,一个能正常运行,一个报语法错误,
不知哪里出错了。
@array = qw(This is Hello World);
$blank = " ";
@result = map {$blank,$_,"\n"} @array ...



[Copy to clipboard] [ - ]
CODE:
@result = map {+" ",$_,"\n"} @array;

perldoc -f map |less -p '"\{" starts'

QUOTE:
"{" starts both hash references and blocks, so "map { ..." could be either the start of map BLOCK LIST or  map EXPR, LIST. Because perl doesn't look ahead for the closing "}" it has to take a guess at which its dealing with based what it finds just after the "{". Usually it gets it right, but if it doesn't it won't realize something is wrong until it gets to the "}" and encounters the missing (or unexpected) comma. The syntax error will be reported close to the "}" but you'll need to change something near the "{" such as using a unary "+" to give perl some help:

Many thanks
perldoc是个好东西
看到这么一个例子, 加上+号貌似就可以了.

%hash = map { +"\L$_", 1  } @array  # perl guesses BLOCK. right
map BLOCK 的 BLOCK 用的是 list context,因此其中的 ,  就成了 list argument spearator,最后原来 @array 中的一个成员会变成 @result 中的三个成员。