Smart Match Precedence
Now that you’ve seen how the smart match operator can save you a lot of work, you just need to know how to tell which sort of match it will do. For that you have to check the table in the perlsyn documentation under “Smart matching in detail.” Table 15-1 shows some of the things the smart match operator can do.
Table 15-1. Smart match operations for pairs of operands
Example | Type of match |
|---|---|
| Hash keys identical |
| At least one key in
|
| At least one key matches pattern |
| Hash key existence exists
|
| Arrays are the same |
| At least one element matches pattern |
| At least one element is 123, numerically |
| At least one element is
|
|
|
| Pattern match |
| Numeric equality with “numish” string |
| String equality |
| Numeric equality |
When you use the smart match operator, Perl goes to the top of the chart and starts looking for a type of match that corresponds to its two operands. It then does the first type of match it finds. The order of the operands doesn’t matter. For instance, you have an array and a hash with the smart match:
use 5.010;
if( @array ~~ %hash ) { ... }Perl first finds the match type for a hash and an array, which
checks that at least one of the elements of @array is a key in %hash. That one is easy because there is only one type of match for those two operands. What ...