perl智能匹配

來源:互聯網
上載者:User

1.perl中~~為智能匹配,它可以智能地根據符號兩側的運算元來確定操作。

如要判斷某個元素是否存在於數組中,不使用智能匹配,程式像這樣:

my $x=2;my @array=(1,2,3);my $flag=0;for (@array){if($x==$_){$flag=1;}}if($flag == 1){print "$x is in the array";}else{print "$x is not in the array";}

使用智能匹配,程式像這樣:

my $x=2;my @array;if(@array~~$x){print "$x is in the array";}else{print "$x is in the array";}

再如查看雜湊表中是否存在某個索引值

‘hello’~~{hello=>1,world=>2} 結果為true

2.智能匹配的優先順序在perl的線上文檔中,智能匹配會按照表格的順序選擇匹配,優先順序從上到下逐漸降低。

     $a      $b        Type of Match Implied    Matching Cod    ======  =====     =====================    =============    Hash    Hash      hash keys identical      [sort keys %$a]~~[sort keys %$b]    Hash    Array     hash slice existence     grep {exists $a->{$_}} @$b    Hash    Regex     hash key grep            grep /$b/, keys %$a    Hash    Any       hash entry existence     exists $a->{$b}    Array   Array     arrays are identical[*]    Array   Regex     array grep               grep /$b/, @$a    Array   Num       array contains number    grep $_ == $b, @$a    Array   Any       array contains string    grep $_ eq $b, @$a    Any     undef     undefined                !defined $a    Any     Regex     pattern match            $a =~ /$b/    Code()  Code()    results are equal        $a->() eq $b->()    Any     Code()    simple closure truth     $b->() # ignoring $a    Num     numish[!] numeric equality         $a == $b    Any     Str       string equality          $a eq $b    Any     Num       numeric equality         $a == $b    Any     Any       string equality          $a eq $b

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.