2016-01-26 5 views
5

私は次のコードを実行すると:内部セミコロンと外側プロミスオブジェクト

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 

+3

' {...} 'は裸のブロックで、サブルーチンに似ています。 –

+0

ありがとうございました – smith

答えて

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) 

2行目は、このように書き直すことができる:

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

は実際には2つの文です:

say "2 seconds are over!"; # normal statement 
'result';     # useless statement in this context (hence the warning) 

は、1行に複数のステートメントを置くことはほとんど彼らがどのように振る舞うか変化しない:

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! 
関連する問題