The smart match operator, ~~
, compares two operands and returns a true value if they match. The fuzziness of the definition demonstrates the smartness of the operator: the type of comparison depends on the type of both operands. given
(given_when) performs an implicit smart match.
The smart match operator is an infix operator:
The type of comparison generally depends first on the type of the right operand and then on the left operand. For example, if the right operand is a scalar with a numeric component, the comparison will use numeric equality. If the right operand is a regex, the comparison will use a grep or a pattern match. If the right operand is an array, the comparison will perform a grep or a recursive smart match. If the right operand is a hash, the comparison will check the existence of one or more keys. A large and intimidating chart in perldoc perlsyn
gives far more details about all the comparisons smart match can perform.
A serious proposal for 5.16 suggests simplifying smart match substantially. The more complex your operands, the more likely you are to receive confusing results. Avoid comparing objects and stick to simple operations between two scalars or one scalar and one aggregate for the best results.
With that said, smart match can be useful:
Smart match works even if one operand is a reference to the given data type:
Hey! The above document had some coding errors, which are explained below:
- Around line 3:
-
A non-empty Z<>