Friday, October 19, 2012

Rediscovering smart match

Perl's "smart match" operator came with Perl 5.10 in 2007 (as a matter of fact, it was released during the French Perl Workshop 2007, and this is where I also learned about this new feature). I immediately thought : "Wow, this is great, it is going to dramatically change my way of programming!".

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 of 

  if ($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 of

  my $string = $hashref->{some_field} || '';
  if ($string eq 'foo') {...}

write

  if ($hashref->{some_field} ~~ 'foo') {...}

No need to test for numish

Instead of

  use 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) {...}

1 comment:

  1. 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:

    http://grokbase.com/g/perl/perl5-porters

    ReplyDelete