当我运行以下代码时:
my $timer = Promise.in(2);
my $after = $timer.then({ say "2 seconds are over!"; 'result' });
say $after.result; # 2 seconds are over
# result
我得到了
2 seconds are over!
result
;
中then
的作用是什么?如果我写
say "2 seconds are over!"; 'result';
我是否收到以下错误?
WARNINGS:
Useless use of constant string "result" in sink context (line 1)
2 seconds are over!
而不是:
2 seconds are over!
result
和第一个例子一样?
答案 0 :(得分:6)
'result'
是块{ say "2 seconds are over!"; 'result' }
的最后一个语句。在Perl语言中,分号(不是换行符)决定了大多数语句的结尾。
在此代码中:
my $timer = Promise.in(2);
my $after = $timer.then({ say "2 seconds are over!"; 'result' }); # 'result' is what the block returns
say $after.result; # 2 seconds are over (printed by the say statement)
# result ('result' of the block that is stored in $after)
第二行可以改写:
my $after = $timer.then( {
say "2 seconds are over!";
'result'
}
); # 'result' is what the block returns
该分号只是结束语句say "2 seconds are over!"
。
在一个区块之外,这一行
say "2 seconds are over!"; 'result';
实际上是两个陈述:
say "2 seconds are over!"; # normal statement
'result'; # useless statement in this context (hence the warning)
将多个语句放在一行中很少会改变它们的行为方式:
my $timer = Promise.in(2); my $after = $timer.then({ say "2 seconds are over!"; 'result' }); say $after.result; # Still behaves the same as the original code. ... Do not edit. This is intentionally crammed into one line!