#navi_header|Perl| - subroutineへの参照を保持する変数と、無名関数の生成を利用し、関数への参照を引数で受け取り、呼び出す関数というトリック例 - <= Perl 5.8 - funcref1.pl #!/usr/bin/perl use strict; use warnings; use Data::Dumper; # Normal Subroutine. sub func1 { print "In func1\n"; } # Reference to Anonymous subroutine. my $func2 = sub { print "In func2\n"; }; sub func3 { print "In func3\n"; } # Function using Prototype. sub func_all($$;$) { my($f1, $f2, $f3) = @_; $f1->(); # how to call subroutine by reference. $f2->(); $f3->() if defined($f3); } &func_all(\&func1, $func2); # ^^ how to access refernce of subroutine body. my $hoge_f = \&func3; # get reference. &func_all(\&func1, $func2, $hoge_f); - 出力 C:\in_vitro\perl\lang>perl ./funcref1.pl In func1 In func2 <------ ここまでが一回目のfunc_all. In func1 In func2 In func3 <------ 2回目のfunc_allでは、func3も呼んでいる。 無名関数と、関数へのリファレンスを保持できるというのは、Perl-OOPやPerl-COP(Context Oriented Programming)、そしてPerlの美しさで非常に重要な役割を果たしている、に違いない。 #navi_footer|Perl|