📘 Smartmatch operator ~~ in Perl 6

📘 Smartmatch operator ~~ in Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


~~ is the smartmatch operator. It compares the objects and tries to work correctly with the operands of any type (that is why the operator is called smart).

say 42 ~~ 42.0; # True
say 42 ~~ "42"; # True

The result of the smartmatching depends on the operand order.

Consider the following:

say "42.0" ~~ 42; # True
say 42 ~~ "42.0"; # False

That behaviour is explained by how the operator works internally. First, it calculates the value of the right-hand side operand; then it calls the ACCEPTS method on it, passing it the variable $_ with a reference to the left-hand side operand. Each data type defines its own variant of the ACCEPTS method. For example, it compares strings in the Str class, and integers in the Int class.

The preceding two examples may be re-written as the following form, where the asymmetry is clearly visible:

say 42.ACCEPTS("42.0"); # True
say "42.0".ACCEPTS(42); # False

Leave a Reply