Corinna classes with the overload pragma #109
-
Reading Will this Just Work (assuming I follow the instructions in that perldoc), or has something equivalent been considered for the roadmap? And assuming it Just Works, would it be best practice to implement the referenced functions for each operator with the method keyword or the sub keyword? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
It Just Works. There are a few caveats when using the new syntax:
use feature 'class';
no warnings 'experimental';
class V {
use overload
'-' => '_neg',
'<=>' => '_compare',
;
field $x :param;
field $y :param;
method squared_length {
return $x*$x + $y*$y;
}
# note: method _neg () fails at runtime.
method _neg (@) {
return __PACKAGE__->new(
x => -$x,
y => -$y,
);
}
# note: you need a method call to access the fields of $other
method _compare ($other,$swap) {
return $self->squared_length <=> $other->squared_length;
}
}
use Test::More;
my $v1 = V->new(x => 1, y => -1);
my $v2 = V->new(x => -1, y => -1);
ok($v1 == $v2, "Vectors have same length");
my $v3 = -$v1;
ok($v1 == $v3, "Negation preserves size");
done_testing; |
Beta Was this translation helpful? Give feedback.
It Just Works.
There are a few caveats when using the new syntax:
method
keyword automatically enables signatures. If you use them, keep in mind that all overloaded methods (even unary ones) are called with three parameters. This is the same as with feature 'signatures' in old style classes, though.