クラスのパッケージ stash を新しい名前にエイリアスできます。
use strict; use warnings; use feature 'say';
package Foo;
sub new { bless [] => shift }
sub hi { say "hi from Foo" }
package main;
# Alias the package to a new name:
local *F:: = *Foo::; # it could make sense to drop the "local"
# make an objects
my $f = F->new;
# say hi!
say $f;
$f->hi;
出力:
Foo=ARRAY(0x9fa877c)
hi from Foo
別の解決策は、必要なパッケージを動的にサブクラス化することです。
use strict; use warnings; use feature 'say';
package Foo;
sub new { bless [] => shift }
sub hi { say "hi from Foo" }
package Whatever;
# no contents
package main;
# let Whatever inherit from Foo:
# note that I assign, instead of `push` or `unshift` to guarantee single inheritance
@Whatever::ISA = 'Foo';
# make an objects
my $w = Whatever->new;
# say hi!
say $w;
$w->hi;
出力:
Whatever=ARRAY(0x9740758)
hi from Foo
これらのソリューションはどちらも実行時に機能し、非常に柔軟です。2 番目の解決策は、より少ない魔法に依存しており、よりクリーンに見えます。ただし、モジュールref($obj) eq 'Foo'
が正しい の代わりにテストblessed $obj and $obj->isa('Foo')
する可能性があり、破損の原因となる可能性があります。