Here's a stupid bug.

Suppose you want to check if a number is either 70 or 73, and your duct-tape-and-chewing gum production environment is stuck in the stone age without the smart-match operator.

You might be tempted to write foo() if $num =~ /^70|73$/, as I did. Oops. That will match 70 and 73, but also anything that ends in 73, like 173 or 273 or foo73. /^(?:70|73)$/ fixes it.

The moral of the story: life sucks without smartmatch.


Um, wouldn't it be even better to write

foo() if $num == 70 or $num == 73;

What Aaron P. said. Isn't a regex (and a complex one with an 'or' pipe in it no less) a lot more overhead than two simple numeric equality comparisons?

use List::MoreUtils 'any';
foo() if any { $_ == $num } 70, 73;

Or if you can’t even install List::MoreUtils, just use core only:

foo() if grep { $_ == $num } 70, 73;

That is what a smart match amounts to as well, of course.

Maybe it is a feature instead of bug?

Well, as long as we're having fun:

bar() if 0==($num*($num-143)+5110)

I might as well put in my 2¢

$num =~ /^7[03]$/;

How would have smart-matching have prevented that?

foo() if $num =~ /^(70|73)$/;

Leave a comment

About Mike Friedman

user-pic Mike Friedman is a professional computer programmer living and working in the New York City area.