@{[]} 这个特性叫什么呢,和ruby的#{}有相关的比较文章吗

18 views
Skip to first unread message

方及道

unread,
Jun 12, 2013, 10:56:49 AM6/12/13
to perl...@googlegroups.com
在print里用了@{ [ expr ] }, 貌似可以在@{ } 里嵌入任意perl代码,不知道这个特性叫什么?

ruby里的#{} 好像方便很多

twcai

unread,
Jun 12, 2013, 11:02:32 AM6/12/13
to perl...@googlegroups.com
[ ]是一个数组引用,@{ }是对应的解引用。
你往数组里扔表达式的话,perl会把表达式的值存入对应的位置而已。

跟你想要的应该不是同一个东西。

方及道

unread,
Jun 12, 2013, 11:07:21 AM6/12/13
to perl...@googlegroups.com
我好像在哪里看过这个特性的,所以进来问问。

你可以测试下下面代码块:

$bool = 0
$a=1;
$b=2;
print <<"_EOC_";
a+b = @{ [ $a+$b ] }
a+b = @{ if (!$bool) { [ $a + $b ] } }
_EOC_

你说的不是我要的。 @{[]} 应该是用字符串解析里面的,和ruby 的 #{} 很像。

在 2013年6月12日星期三UTC+8下午11时02分32秒,twcai写道:

twcai

unread,
Jun 12, 2013, 11:49:20 AM6/12/13
to perl...@googlegroups.com
仍然只是引用和解引用而已。

抱歉我没有学过Ruby所以不清楚#{}在Ruby中扮演的角色。

但是@{[expr]}这个语法并不是为这个场景特别设计的,这只是一个在字符串中插入代码的trick。

twcai

unread,
Jun 12, 2013, 11:51:12 AM6/12/13
to perl...@googlegroups.com
查了一下perldoc,确实有提到这个trick

Here's a trick for interpolating a subroutine call into a string:

  1. print "My sub returned @{[mysub(1,2,3)]} that time.\n";

The way it works is that when the @{...} is seen in the double-quoted string, it's evaluated as a block. The block creates a reference to an anonymous array containing the results of the call to mysub(1,2,3) . So the whole block returns a reference to an array, which is then dereferenced by @{...} and stuck into the double-quoted string. 


On Wednesday, June 12, 2013 11:07:21 PM UTC+8, 方及道 wrote:

Mr.Noodles

unread,
Jun 12, 2013, 11:56:03 AM6/12/13
to perl...@googlegroups.com
good job! 

3Q!

--
您收到此邮件是因为您订阅了 Google 网上论坛“PerlChina Mongers 讨论组”中的主题。
要退订此主题,请访问 https://groups.google.com/d/topic/perlchina/K5yBGT3JgI4/unsubscribe?hl=zh-CN。
要退订此论坛及其所有主题,请发送电子邮件到 perlchina+...@googlegroups.com
要向此网上论坛发帖,请发送电子邮件至 perl...@googlegroups.com
通过以下网址访问此论坛:http://groups.google.com/group/perlchina?hl=zh-CN。
要查看更多选项,请访问 https://groups.google.com/groups/opt_out。
 
 

Reply all
Reply to author
Forward
0 new messages