perl 继承概述

<pre name="code" class="html">[root@wx03 test]# cat Horse.pm 
package Horse;
##Horse继承了Critter类,Critter这里是基类或者父类
use base qw(Critter);
sub new {
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my $self = {
color => "bay",
legs => 4,
owner => 'scan',
@_, # 覆盖以前的属性
};
return bless $self, $class;
#return  $self;
};
sub sum1 {
       $self=shift;
       my $a=shift;
       my $b=shift;
       return $a + $b + 7;
};

our @arr=qw/1 2 3 4 5 6 7/;
our %h1=(1,2,3,4,5,6,7,8);
1;

[root@wx03 test]# cat Critter.pm 
package Critter;


sub sum2 {
       $self=shift;
       my $a=shift;
       my $b=shift;
       return $a + $b;
};


sub fun1 {
       $self=shift;
       message::message($self);
};


sub fun2 {
       $self=shift;
       $var='bosdadada';
       return $var;
};
sub on_receive_msg:lvalue{
      $self=shift;
      $self->{name}="aabbccdd123141242";
      $self->{on_receive_msg};
};

our $str="12312";
1;

/*******************
[root@wx03 test]# cat t10.pl 
unshift(@INC,"/root/test"); 
use Horse;;
my $ua=Horse->new();


my $str=$ua->fun2();
print $str;
print "\n";


[root@wx03 test]# perl t10.pl 
bosdadada


如果去掉Horse类里的继承:

package Horse;
#use base qw(Critter);
sub new {
my $invocant = shift;

[root@wx03 test]# perl t10.pl 
Can't locate object method "fun2" via package "Horse" at t10.pl line 6.

提示找不到fun2方法


/***********************
[root@wx03 test]# cat t10.pl 
unshift(@INC,"/root/test"); 
use Horse;;
my $ua=Horse->new();


my $str=$ua->fun1();
print $str;
print "\n";

[root@wx03 test]# perl t10.pl 
Undefined subroutine &message::message called at Critter.pm line 15.


没有use message;:

package Critter;
#use message;


sub sum2 {
       $self=shift;
       my $a=shift;
       my $b=shift;
       return $a + $b;
};


sub fun1 {
       $self=shift;
       message::message($self);
};



解决方案:

1):
package Critter;
##继承message类
use base qw/message/;


sub sum2 {
       $self=shift;
       my $a=shift;
       my $b=shift;
       return $a + $b;
};


sub fun1 {
       $self=shift;
       $self->message();
};



2):
package Critter;
use message;


sub sum2 {
       $self=shift;
       my $a=shift;
       my $b=shift;
       return $a + $b;
};


sub fun1 {
       $self=shift;
       message::message($self);
       # $self->message();
};







   

posted @ 2016-05-27 09:39  czcb  阅读(121)  评论(0编辑  收藏  举报