kart1657 kart1657 - 5 months ago 35
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


use strict;
package math;

sub new
my $class=shift;
my $self={};
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 ;


below is the script from where im calling the parent class
in a derived class called

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();


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:

addition: 2
multiplication: 1

in above script i'm not able to fetch values into
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();


addition: 47
multiplication: 552
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download