加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl智能匹配

发布时间:2020-12-15 23:57:42 所属栏目:大数据 来源:网络整理
导读: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 arr

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读