A little nicer way to use smartmatch on perl 5.18


Of course as Perl developers we all love new features, don't we?

So the moment we could work with perl 5.10 we all started using smartmatch, right? If not for the only reason it allows us to write elegant code like this:

use v5.10.1;
@array = qw ( Thom Jonny Colin Ed Phil );
say "I found Phil!" if 'Phil' ~~ @array;

But now we have perl 5.18 and some of the ideas of smartmatch turned out to be a little too smart, and so we now consider it an experimental feature. So even code like this, when executed on a 5.18 perl, gives warnings:

Smartmatch is experimental at smart.pl line 3.
I found Phil!

brian d foy wrote about how to stop these warnings, but it's not pretty:

no warnings 'experimental::smartmatch';

This works under perl 5.18 but gives nasty error messages under older perls:

Unknown warnings category 'experimental::smartmatch' at smart.pl line 3.
BEGIN failed--compilation aborted at smart.pl line 3.

so the 'best' way to do it is like below:

no if $] >= 5.017011, warnings => 'experimental::smartmatch';

Ugly, right? That is why Leon Timmermans created experimental, a CPAN module that allows you to simply write:

use experimental 'smartmatch';

That's much better! I can remember that, and it's readable. I hope you like it as much as I do!

Of course this does not alleviate the problem that smartmatch is now considered experimental, which means that its implementation is probably going to change in upcoming perls.


If you want to alleviate the possibility of smartmatch changing in newer Perls, you could try match::smart which is aimed at providing a not-quite-drop-in replacement for smartmatch (but with stable behaviour - it won't change in future Perls).

Excellent! I updated my post.

One of the features that I miss most comparing with Python is the keyword 'in'. It would make the code of checking the belongingness so elegant. I felt excited when the smart match '~~' came in Perl but feel sad that its volatile.

Anyway, the match::smart or match::simple packages make me happy again. Thank you so much, the author!

This is very handy for those cases where smartmatch is still useful, like when matching against literal strings and lists like the example you gave.

Leave a comment

About Mike B

user-pic I blog about Perl.