gpt4 book ai didi

promise - Promise 对象内外的分号

转载 作者:行者123 更新时间:2023-12-04 18:35:53 31 4
gpt4 key购买 nike

当我运行以下代码时:

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

像第一个例子?

最佳答案

'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!

关于promise - Promise 对象内外的分号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35020211/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com