1、XXX.pm 文件里面的第一行要是:package XXX;
2、要有构造函数 sub new,实现如下:
sub new {
my $class = shift; # Get the request class name
my $self = {};
my ($name)=@_;
my $self = {
"name" =>$name
};
bless $self, $class; # Use class name to bless() reference
return $self;
}
3、接着用sub YYY{} 定义自己的函数
例如:
sub setBeanType{
my ($class, $name) = @_;//传进来的第一个参数是类似c++的this指针,第二个才是真正的参数
$class->{'Bean'} = $name;
print "Set bean to $name
";
}
[root@wx03 test]# cat p1.pm
package p1;
use Data::Dumper;
sub new {
my $self = {};
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my ($name)=@_;
my $self = {
"name" =>$name
};
bless $self, $class; # Use class name to bless() reference
print "111111111111111111
";
$str=Dumper($self);
print "$str is $str
";
return $self;
};
sub setBeanType{
my ($self, $name) = @_;##//传进来的第一个参数是类似c++的self指针,第二个才是真正的参数
$self->{'Bean'} = $name;
print "Set bean to $name
";
$str=Dumper($self);
print "$str is $str
";
};
1;
[root@wx03 test]# cat p1.pm
package p1;
use base qw(p2);
use Data::Dumper;
sub new {
my $self = {};
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my ($name)=@_;
my $self = {
"name" =>$name
};
bless $self, $class; # Use class name to bless() reference
print "111111111111111111
";
$str=Dumper($self);
print "$str is $str
";
return $self;
};
sub setBeanType{
my ($self, $name) = @_;##//传进来的第一个参数是类似c++的self指针,第二个才是真正的参数
$self->{'Bean'} = $name;
print "Set bean to $name
";
$str=Dumper($self);
print "$str is $str
";
};
1;
[root@wx03 test]# cat p1.pl
unshift(@INC,"/root/test");
require p1;
$ua=p1->new('lily');
print "2222222222222222
";
$str=$ua->setBeanType(scan);
[root@wx03 test]# perl p1.pl
111111111111111111
$str is $VAR1 = bless( {
'name' => 'lily'
}, 'p1' );
2222222222222222
Set bean to scan
$str is $VAR1 = bless( {
'Bean' => 'scan',
'name' => 'lily'
}, 'p1' );
不断的填充这个对象:
使用基类:
use base 是面向对象编程时,用来描述“基类”的: