Unfortunately, our infrastructure at work still remained Perl 5.8 for several years, and by the time I was at last able to make use of smart match, I had nearly forgotten all its virtues. I have a couple of lines of code with "given/when" statements, but that's mostly it.
However, after having recently attended the excellent class by Damian Conway on Advanced Perl Programming Techniques, smart match came back to my mind. I know, it's been criticized for being too complex in some of its matching rules; but the basic rules are great and yield more readable and more flexible code.
Here are some examples that I'm refactoring right now :
List membership
Instead ofif ($data =~ /^(@{[join '|', @array]})$/) {...}
or
use List::MoreUtils qw/any/;
if (any {$data eq $_} @array) {...}
write
if ($data ~~ @array) {...}
No need to test for undef
Instead ofmy $string = $hashref->{some_field} || '';
if ($string eq 'foo') {...}
write
if ($hashref->{some_field} ~~ 'foo') {...}
No need to test for numish
Instead ofuse Scalar::Util qw/looks_like_number/;
my $both_nums = looks_like_number($x)
&& looks_like_number($y);
if ($both_nums ? $x == $y : $x eq $y) {...}
write
if ($x ~~ $y) {...}
Beware of possible upcoming changes to smartmatch. Try searching the Perl 5 Porters mailing list to see the ongoing discussion. Here's a link to P5P archives with a nicely functioning search:
ReplyDeletehttp://grokbase.com/g/perl/perl5-porters