kart1657 kart1657 - 27 days ago 9
Perl Question

How to set and get using class in perl?

Im trying to set and get the values in the perl using classes.

below is my parent class

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;


below is the script from where im calling the parent class
math
in a derived class called
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";


improper output:

$num1:1
$num2:1
addition: 2
multiplication: 1


in above script i'm not able to fetch values into
$num1
and
$num2
using
get_number
sub routine.

Where am i going wrong?

Answer Source

Turn on warnings and it'll tell you:

"my" variable $self masks earlier declaration in same scope at line 17.

You need to change:

sub set_number {
   my $self = shift;
   my $self->{'num'} = shift;
}

That second my is what's breaking it, because it's creating a new instance of $self.

Also: my $num = print ..

Is almost certainly not doing what you want it to - it's setting $num to the return code of print.

Try instead:

my $num1 =  $number_obj1->get_number();
my $num2 =  $number_obj2->get_number();

Output:

$num1:23
$num2:24
addition: 47
multiplication: 552