Overloading operators for a class
class A {
has $.val;
method Str { $!val ~ 'µ' }
}
multi infix:<~>(A:D $lhs, A:D $rhs) {
('(', $lhs.val, ',', $rhs.val, ')', 'µ').join;
}
dd A.new(val => "A") ~ A.new(val => "B"); # "(A,B)µ"
So yes, that is the correct way. If you want to override +
, then the name of the sub to create is infix:<+>
.
You can also provide the case for type objects by using the :U
"type smiley", e.g.:
multi infix:<~>(A:U $lhs, A:U $rhs) {
'µ'
}
Hope this answers your question.
In Perl 6, operators are considered part of the current language. All things that relate to the current language are defined lexically (that is, my
-scoped). Therefore, a multi
sub is the correct thing to use.
If putting this code in a module, you would probably also want to mark the multi
for the operator with is export
:
multi infix:<~>(A:D $lhs, A:D $rhs) is export {
('(', $lhs.val, ',', $rhs.val, ')', 'µ').join;
}
So that it will be available to users who use
or import
the module (use
is in fact defined in terms of import
, and import
imports symbols into the lexical scope).
While there are some operators that by default delegate to methods (for example, prefix:<+>
calls Numeric
), there's no 1:1 relation between the two, and for most operators their implementation is directly in the operator sub
(or spread over many multi sub
s).
Further, the set of operators is open, so one is not restricted to overloading existing operators, but can also introduce new ones. This is encouraged when the new meaning for the operator is not clearly related to the normal semantics of the symbol used; for example, overloading +
to do matrix addition would be sensible, but for something that couldn't possibly be considered a kind of addition, a new operator would be a better choice.