Reputation: 1275
So I have a class AClass with variables (x, y), and a function which should take two objects as arguments of the same class, compute their x and y, and return a new instance of the class with computed values.
package AClass;
sub new {
my $class = shift;
my $x = shift;
my $y = shift;
my $self = {
x => $x,
y => $y
};
return bless($self, $class);
}
sub getX {
my $self = shift;
return $self->{'x'};
}
sub getY {
my $self = shift;
return $self->{'y'};
}
sub addition {
my ($c1, $c2) = @_;
return new AClass(
$c1->getX() + $c1->getX(),
$c1->getY() + $c2->getY()
);
}
my $a1 = AClass->new(6, 4);
my $a2 = AClass->new(4, 3);
my $val = AClass::addition(\$v1, \$v2);
say $val.getX();
I'm getting error "Can't call method "getX" on unblessed reference". I think the problem is in addition function, when I'm trying to access the values of the objects which are not the real numbers or ?
Upvotes: 0
Views: 130
Reputation: 126722
There is a number of problems here.
You are using $v1
and $v2
when presumably you mean $a1
and $a2
You are passing references to those objects, instead of the objects themselves
Your addition
method adds the X value of $c1
to itself instead of to the X
value of $c2
You are using the string concatenation operator .
instead of the indirection operator ->
It is best to use lower-case letters for lexical identifiers. Capitals are generally reserved for globals like package names
You must always use strict
and use warnings
at the top of your program. In this case you would have been alerted to the fact that $v1
and $v2
hadn't been declared.
This version of your code works fine
use strict;
use warnings;
package AClass;
sub new {
my $class = shift;
my ($x, $y) = @_;
bless { x => $x, y => $y }, $class;
}
sub get_x {
my $self = shift;
$self->{x};
}
sub get_y {
my $self = shift;
$self->{y};
}
sub addition {
my ($c1, $c2) = @_;
AClass->new(
$c1->get_x + $c2->get_x,
$c1->get_y + $c2->get_y
);
}
package main;
use feature 'say';
my $a1 = AClass->new(6, 4);
my $a2 = AClass->new(4, 3);
my $val = AClass::addition($a1, $a2);
say $val->get_x;
output
10
Upvotes: 5
Reputation: 385546
You use $v1
instead $a1
. Always use use strict; use warnings;
.
Also, you're taking a reference for no reason.
my $val = AClass::addition($a1, $a2);
The following would also work (though add
) would be a better word:
my $val = $a1->addition($a2);
Upvotes: 3