📘 Smartmatch operator ~~ in Perl 6

~~ 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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s