一些命名空间长而烦人.假设我下载了一个名为FooFoo-BarBar-BazBaz.tar.gz的假设包,它包含以下模块:
FooFoo::BarBar::BazBaz::Bill FooFoo::BarBar::BazBaz::Bob FooFoo::BarBar::BazBaz::Ben FooFoo::BarBar::BazBaz::Bozo FooFoo::BarBar::BazBaz::Brown FooFoo::BarBar::BazBaz::Berkly FooFoo::BarBar::BazBaz::Berkly::First FooFoo::BarBar::BazBaz::Berkly::Second
有没有一个可以使用的模块或技术,类似于C’using’语句,就是有办法可以做
using FooFoo::BarBar::BazBaz;
那会让我做的
my $obj = Brown->new(); ok $obj->isa('FooFoo::BarBar::BazBaz::Brown') ; # true # or... ok $obj->isa('Brown'); # also true
解决方法
aliased pragma这样做:
use aliased 'FooFoo::BarBar::BazBaz::Bill'; my $bill = Bill->new;
别名是语法糖
use constant Bill => 'FooFoo::BarBar::BazBaz::Bill'; # or sub Bill () {'FooFoo::BarBar::BazBaz::Bill'}
这样做的缺点是,包名称作为参数的正常使用是用引用的字符串来完成的:
$obj->isa('FooFoo::BarBar::BazBaz::Bill')
但是,常量子程序需要一个光明的词语:
$obj->isa(Bill);
这似乎就像一个等待发生的bug.
或者,您可以使用Perl的内置命名空间别名支持:
package Foo::Bar::Baz::Bill; sub new {bless {}} package Foo::Bar::Baz::Tom; sub new {bless {}} package main; BEGIN {*FBB:: = *Foo::Bar::Baz::} # the magic happens here say FBB::Bill->new; # Foo::Bar::Baz::Bill=HASH(0x80fd10) say FBB::Tom->new; # Foo::Bar::Baz::Tom=HASH(0xfd1080)
关于 – > isa(‘shortname’)的要求,别名的隐藏方法与往常引用的字符串一样工作:
my $obj = FBB::Bill->new; say $obj->isa('FBB::Bill'); # prints 1 say $obj->isa('Foo::Bar::Baz::Bill'); # prints 1
编译时别名BEGIN {* short :: = * long :: package :: name ::}的效果在所有包和范围之间都是全局的.只要你选择一个空的包来进入别名就行了.