文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>perl的实验阶段特性: attribute

perl的实验阶段特性: attribute

时间:2006-12-25  来源:xiaoshengcaicai

<>

参考文档
http://search.cpan.org/~nwclark/perl-5.8.8/lib/attributes.pm

Catalyst里面的模块的函数都有attribute,比如Private,default,local,global

从文档来看,目前perl函数支持3种内置属性,locked,lvalue,method。

对于函数,可以自定义属性,初步实验代码如下:

CODE:
[Copy to clipboard]
package TestA;
sub hello :  good : bad{
        print "hello\n";
}
1; perl -c TestA.pm , 发现编译错误Invalid CODE attributes: good : bad at TestA.pm

修改代码如下:

CODE:
[Copy to clipboard]
package TestA;
sub hello :  good : bad{
        print "hello\n";
}

sub MODIFY_CODE_ATTRIBUTES {
}
1; perl -c TestA.pm , 发现没有错误了,于是推断perl在编译函数时,发现了用户自定义的属性时,会自动调用名字空间里面的MODIFY_CODE_ATTRIBUTES(),如果不存在该函数,将发生编译错误。

为了将函数的属性能存储起来,同时能进行读取,修改代码为:

CODE:
[Copy to clipboard]
package TestA;

use strict;

use base qw/Class::Data::Inheritable/;

__PACKAGE__->mk_classdata('all_attribute');
__PACKAGE__->all_attribute({});

sub MODIFY_CODE_ATTRIBUTES {
    my ( $class, $code, @attrs ) = @_;
    $class->all_attribute({$code => [@attrs]});
    return ();
}

sub FETCH_CODE_ATTRIBUTES {
        my ($class, $code) = @_;       
        return $class->all_attribute->{$code};
}

sub hello : good : bad{
        print "hello\n";
}

use attributes;
use Data::Dumper qw/Dumper/;
my @attr = attributes::get(\&hello);
print Dumper(@attr);

1; perl -c TestA.pm, 发现竟然有问题Can't locate object method "all_attribute" via package "TestA" at TestA.pm

原来__PACKAGE__->mk_classdata('all_attribute');这行代码时运行时执行,那么 all_attribute()是在运行时才添加到名字空间里面,而perl在编译的时候就要调用MODIFY_CODE_ATTRIBUTES ,所以自然发现all_attribute不存在

于是只好另外改代码如下:

CODE:
[Copy to clipboard]
package TestA;

use strict;

use base qw/Class::Data::Inheritable/;

__PACKAGE__->mk_classdata('all_attribute');
__PACKAGE__->all_attribute({});

sub MODIFY_CODE_ATTRIBUTES {
    my ( $class, $code, @attrs ) = @_;
    $class->all_attribute({$code => [@attrs]});
    return ();
}

sub FETCH_CODE_ATTRIBUTES {
        my ($class, $code) = @_;       
        return $class->all_attribute->{$code};
}
1;

CODE:
[Copy to clipboard]
package  TestB;
use base qw/TestA/;
sub hello : good : bad{
        print "hello\n";
}

use attributes;
use Data::Dumper qw/Dumper/;
my @attr = attributes::get(\&hello);
print Dumper(@attr);

1; perl -c TestB.pm ,输出结果:

QUOTE:
$VAR1 = [
          'good',
          'bad'
        ];
排行榜 更多 +
泡龙大闯关安卓版

泡龙大闯关安卓版

冒险解谜 下载
割草派对安卓版

割草派对安卓版

飞行射击 下载
堡垒攻防战安卓版

堡垒攻防战安卓版

飞行射击 下载