« Binding.pm implemented | Home | Mac OS X Security Update 2009-001 可能會破壞你的 Perl (CPAN) »

January 9, 2009

Sub::Alias - 替函式取別名

最近在寫的 Sub::Alias 模組能夠很便利地替函式取別名:

use Sub::Alias;

sub name { "..." }

alias get_name => 'name';

比較熟習 Perl 的人大概可以看出來其實這就是:

*get_name = \&name;

但是好懂多了。

剛剛釋出了 0.03 版,增加了對 runtime 的支援:

sub alias_another_sub {
    my $new_name = shift;

    alias $new_name => 'another_sub';     
}

alias_another_sub_to( "hey" );

如果用 Perl 原本的做法,這相當於:

no strict;
*{"$new_name"} = \&another_sub;

是的,在執行時期操弄 symbol table,就必需要關掉 strict 才行。

這個模組只算是個小幫手,不過實做它卻出乎意料地有點難度,需要使用 Devel::BeginLiftDevel::Declare 兩個模組,在編輯時期操弄 symbol table,甚至是注入新的原始碼。

1 TrackBack

TrackBack URL: http://chupei.pm.org/mt/mt-tb.cgi/527

最近在寫的 Sub::Alias 模組能夠很便利地替函式取別名: use Sub::Alias; sub name { "..." } alias get_name => 'name'; 閱讀全文。... Read More

Leave a comment

Pages

OpenID accepted here Learn more about OpenID

About this Entry

This page contains a single entry by gugod published on January 9, 2009 9:40 PM.

Binding.pm implemented was the previous entry in this blog.

Mac OS X Security Update 2009-001 可能會破壞你的 Perl (CPAN) is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.