我尝试使用类设置并获取perl中的值。
下面的是我的父类math.pm
。
use strict;
package math;
sub new
{
my $class=shift;
my $self={};
bless($self,$class);
return $self;
}
sub set_number
{
my $self=shift;
my $self->{'num'}=shift;
}
sub get_number
{
my $self=shift;
return $self->{'num'};
}
sub add
{
my $self=shift;
my $num1=shift;
my $num2=shift;
return $num1 + $num2;
}
sub multiply
{
my $self=shift;
my $num1=shift;
my $num2=shift;
return $num1 * $num2 ;
}
1;
下面是我在名为math
的派生类中调用父类operations
的脚本
use strict;
use math;
package operations;
our @ISA = qw/math/;
my $number_obj1=operations->new();
my $number_obj2=operations->new();
my $number_obj3=operations->new();
$number_obj1->set_number("23");
$number_obj2->set_number("24");
my $num1=print $number_obj1->get_number();
my $num2=print $number_obj2->get_number();
print "\n\$num1:$num1\n\$num2:$num2\n";
print "addition: ",$number_obj3->add("$num1","$num2"),"\n";
print "multiplication: ",$number_obj3->multiply("$num1","$num2"),"\n";
输出不正确:
$num1:1
$num2:1
addition: 2
multiplication: 1
在上面的脚本中,我无法使用$num1
子例程将值提取到$num2
和get_number
。
我哪里错了?
答案 0 :(得分:2)
开启warnings
,它会告诉您:
"my" variable $self masks earlier declaration in same scope at line 17.
您需要更改:
sub set_number {
my $self = shift;
my $self->{'num'} = shift;
}
第二个my
正在破坏它,因为它正在创建$self
的新实例。
另外:my $num = print ..
几乎肯定没有按照您的意愿行事 - 它将$num
设置为print
的返回代码。
尝试改为:
my $num1 = $number_obj1->get_number();
my $num2 = $number_obj2->get_number();
输出:
$num1:23
$num2:24
addition: 47
multiplication: 552