動的関数定義(?)の続き
昨日に引き続き、いろいろ試したのでメモ。
例えば、こんなの。
use strict;
use warnings;
use v5.10;
{
no strict 'refs';
*{foo} = sub {
say 'foo';
};
}
foo();
実行結果はこんな感じ。
$ perl aaa.pl
foo
そういえば、ハッシュだった、気がする。(*1)
あと、パッケージ名を付けるならこんな感じ。
use strict;
use warnings;
use v5.10;
my $pkg = __PACKAGE__;
say $pkg;
{
no strict 'refs';
*{"${pkg}::foo"} = sub {
say 'foo';
};
}
foo();
実行結果はこんな感じ。
$ perl bbb.pl
main
foo
さらに、こんなこんなことも。
$ cat ccc.pl
use strict;
use warnings;
use v5.10;
eval {
foo();
};
if ( $@ ) {
say '--- exception caught! ---';
say $@;
say '-------------------------';
}
sub hoge {
no strict 'refs';
my $caller = caller( 0 );
say '$caller = ', $caller;
*{"${caller}::foo"} = sub {
say 'foo';
};
}
hoge();
foo();
実行結果はこんな感じ。
$ perl ccc.pl
--- exception caught! ---
Undefined subroutine &main::foo called at ccc.pl line 6.
-------------------------
$caller = main
foo
関数をコールしたら、関数が増えたよ!
おしまい。
(*1) シンボリックテーブル?っていうの??
Leave a Comment