あなたは\&subname
構文を使用して、サブルーチンのリファレンスを取ることができ、その後、あなたは簡単にスカラーのような引数として他のサブルーチンに渡すことができます。これはperlsub
とperlref
に記載されています。後でArrow operator(->)
を使用して逆参照することができます。
sub question {
print "question the term";
return 1;
}
my $question_subref = \&question;
answer($question_subref);
sub answer {
my $question_subref = shift;
print "subroutine question is used as parameters";
# call it using arrow operator if needed
$question_subref ->();
return 1;
}
名前を付けないで匿名サブルーチンを作成することもできます。それは興味深い場合につながる可能性があります。closures
my $question = sub {
print "question the term";
return 1;
};
answer($question);
# you can call it using arrow operator later.
$question ->();
「戻る」の後にかっこは必要ありません。もっと重要なのは、 'return;(何もせずに)実際には' undef'を返すことです。すべてがうまくいったことを示したければ - これはいつも良いアイデアです - 通常は 'return 1;'を行います。 – zdim
@zdimのみスカラーコンテキスト – ysth
@ysthはい、良い点、ありがとう。リストの文脈では、この意味では別のゲームです。 – zdim