English 中文(简体)
Perl ala Haskell的配对模式
原标题:Pattern matching in Perl ala Haskell

In Haskell (F#, Ocaml等),我可以这样做:

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

计算特定分类的标识。

这可以简明扼要地表达某些逻辑流动;我曾碰到了Perl的这种流动。

我现在正在做的事情

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");
}

那些人感到压迫和ug。

该法典必须从Perl 5.8开始,但当然,我也对更现代的技术感兴趣。

最佳回答

这里还有一种可能的办法,它仍然是一种不大的言辞,但也许反映了更好的流动。 (在《最佳做法》一书中,作者建议主要避免<代码>>>>的固定格式。) 因为你需要弄清了解正在发生的事情的权利的一切途径。 如果能帮助强调情况,你可以添加括号。

sub sign
{
    my $x = shift;
    $x  > 0  and return  1;
    $x == 0  and return  0;
    $x  < 0  and return -1;
}

sub frobnicator
{
    my $frob = shift;

    $frob eq "Foomaticator" and return "foo";
    $frob eq "Barmaticator" and return "bar";

    croak("Unable to frob legit value: $frob received");
}
问题回答

您可以使用有条件的经营者:

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

It turns your original example into something like:

sub sign {
  my $x = shift;
  return $x < 0 ? -1 :
         $x > 0 ?  1 :
                   0 ;
}

谁知道,只是多少,但从以下几个方面来看,情况就是如此:

For what it s worth, Perl 5.10 or later gives you:

given

...which would allow:

...
use feature qw( switch say);
use Carp;
sub frobnicator {
    my $frob = shift;
    given ($frob) {
        when ( Foomaticator ) {
            return q(foo);
        }
        when ( Barmaticator ) {
            return q(bar);
        }
        default {
            croak(qq(Unable to frob legit value: $frob received));
        }
    }
}




相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签