Pattern matching in Perl ala Haskell

Posted by Paul Nathan on Stack Overflow See other posts from Stack Overflow or by Paul Nathan
Published on 2011-11-22T23:57:51Z Indexed on 2011/11/23 1:50 UTC
Read the original article Hit count: 388

In Haskell (F#, Ocaml, and others), I can do this:

sign x |  x >  0        =   1
       |  x == 0        =   0
       |  x <  0        =  -1

Which calculates the sign of a given integer.

This can concisely express certain logic flows; I've encountered one of these flows in Perl.

Right now what I am doing is

sub frobnicator
{
   my $frob = shift;
   return "foo" if $frob eq "Foomaticator";
   return "bar" if $frob eq "Barmaticator";
   croak("Unable to frob legit value: $frob received");
}

Which feels inexpressive and ugly.

This code has to run on Perl 5.8.8, but of course I am interested in more modern techniques as well.

© Stack Overflow or respective owner

Related posts about perl

Related posts about coding-style