Pattern matching in Perl ala Haskell
- by Paul Nathan
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.