免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2003 | 回复: 4
打印 上一主题 下一主题

和map相关的一个问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-12-09 23:41 |只看该作者 |倒序浏览
刚开始看<<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平台

[ 本帖最后由 _Erics 于 2008-12-10 00:06 编辑 ]

论坛徽章:
3
戌狗
日期:2014-09-10 17:07:162015年辞旧岁徽章
日期:2015-03-03 16:54:15wusuopu
日期:2016-06-17 17:43:45
2 [报告]
发表于 2008-12-10 04:23 |只看该作者
原帖由 _Erics 于 2008-12-9 23:41 发表
刚开始看
在练习的时候遇到一个问题,两段语义相近的代码,一个能正常运行,一个报语法错误,
不知哪里出错了。
@array = qw(This is Hello World);
$blank = " ";
@result = map {$blank,$_,"\n"} @array ...

  1. @result = map {+" ",$_,"\n"} @array;
复制代码


perldoc -f map |less -p '"\{" starts'
"{" 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:

论坛徽章:
0
3 [报告]
发表于 2008-12-10 09:17 |只看该作者

回复 #2 ynchnluiti 的帖子

Many thanks
perldoc是个好东西

论坛徽章:
0
4 [报告]
发表于 2008-12-10 09:52 |只看该作者

回复 #1 _Erics 的帖子

看到这么一个例子, 加上+号貌似就可以了.

%hash = map { +"\L$_", 1  } @array  # perl guesses BLOCK. right

论坛徽章:
95
程序设计版块每日发帖之星
日期:2015-09-05 06:20:00程序设计版块每日发帖之星
日期:2015-09-17 06:20:00程序设计版块每日发帖之星
日期:2015-09-18 06:20:002015亚冠之阿尔艾因
日期:2015-09-18 10:35:08月度论坛发贴之星
日期:2015-09-30 22:25:002015亚冠之阿尔沙巴布
日期:2015-10-03 08:57:39程序设计版块每日发帖之星
日期:2015-10-05 06:20:00每日论坛发贴之星
日期:2015-10-05 06:20:002015年亚冠纪念徽章
日期:2015-10-06 10:06:482015亚冠之塔什干棉农
日期:2015-10-19 19:43:35程序设计版块每日发帖之星
日期:2015-10-21 06:20:00每日论坛发贴之星
日期:2015-09-14 06:20:00
5 [报告]
发表于 2008-12-10 10:51 |只看该作者
map BLOCK 的 BLOCK 用的是 list context,因此其中的 ,  就成了 list argument spearator,最后原来 @array 中的一个成员会变成 @result 中的三个成员。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP