加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl Class :: Accessor失败,简单的例子 – 为什么?

发布时间:2020-12-15 23:33:04 所属栏目:大数据 来源:网络整理
导读:有人能告诉我为什么main在这个非常小而简单的例子中找不到Class :: Accessor生成的方法吗? 这几行代码失败了 perl codesnippets/accessor.plCan't locate object method "color" via package "Critter" atcodesnippets/accessor.pl line 6. 看代码: #!/opt
有人能告诉我为什么main在这个非常小而简单的例子中找不到Class :: Accessor生成的方法吗?

这几行代码失败了

perl codesnippets/accessor.pl
Can't locate object method "color" via package "Critter" at
codesnippets/accessor.pl line 6.

看代码:

#!/opt/local/bin/perl
# The whole Class::Accessor thing does not work !!

my $a = Critter->new;
$a->color("blue");
$a->display;
exit 0;

package Critter;
    use base qw(Class::Accessor );
    Critter->mk_accessors ("color" );

    sub display {
        my $self  = shift;
        print "i am a $self->color " . ref($self) . ",whatever this word meansn";
    }

解决方法

FM给你很好的建议. mk_accessors需要在其他代码之前运行.此外,通常您将Critter放在单独的文件中并使用Critter加载模块.

这有效,因为use具有编译时效果.做使用小动物;和做BEGIN一样{要求小动物; Critter->进口;这保证了模块的初始化代码将在其余代码编译之前运行.

将多个包放在一个文件中是可以接受的.通常,我会在一个文件中对相关对象进行原型设计,因为它在我进行原型设计时可以很方便地保存所有内容.当时机成熟时,将文件拆分为单独的位也很容易.

因此,我发现将多个包保存在一个文件中并使用它们就像我使用它们一样的最佳方法是将包定义放在以真值结尾的BEGIN块中.使用我的方法,您的示例将被写入:

#!/opt/local/bin/perl

my $a = Critter->new;
$a->color("blue");
$a->display;

BEGIN {
    package Critter;
    use base qw(Class::Accessor );

    use strict;
    use warnings;

    Critter->mk_accessors ("color" );

    sub display {
         my $self = shift;

         # Your print was incorrect - one way:
         printf "i am a %s %s whatever this word meansn",$self->color,ref $self;

         # another:
         print "i am a ",ref $self,"whatever this word meansn";

    }

    1;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读