Perl语言入门——智能匹配与given-wh…

来源:互联网 发布:淘宝店铺信息怎么看 编辑:程序博客网 时间:2024/04/27 20:39
智能匹配操作符:新的智能匹配操作符(~~)会根据需要自己决定用何种方式比较两端的操作数
   以下罗列一些例子
   
    例一
    print "Ifound Fred in the name!\n" if $name=~/Fred/;
    say "I foundFred in the name!\n" if $name ~~ /Fred/;
   
    例二
    my$flag=0;
    foreach my$key(keys %names){
       next unless $key=~/Fred/;
       $flag=$key;
       last;
    }
    print "Ifound a key matching 'Fred'. It was $flag\n" if $flag;
    say "I founda key matching 'Fred'" if %names ~~ /Fred/;
   
    例三
    my$equal=0;
    foreach my$index (0 .. $#names1){
       last unless $names1[$index] eq $names2[$index];
       $equal++;
    }
    print "Thearrrays have the same elements\n" if $equals==@names1;
    say "Thearrays have the same elements\n" if @names1 ~~ @names2;
   使用智能匹配时,对两边操作数的顺序没有要求,倒过来写也行,且满足“交换律”
智能匹配操作的优先级:perlsyn在线手册中“Smart matching in detail”部分
given语句:given-when控制结构能够根据given的参数,执行某个条件对应的语句块,对应C语言的switch
   given($ARGV[0]){
       when(/fred/i){say 'Name has fred in it'}
       when(/^Fred/){say 'Name starts with Fred'}
       when('Fred'){say 'Name is Fred'}
       default {say 'I don't see a Fred'}
    }
   given会将参数化名为$_,每个when条件都尝试用智能匹配对$_进行测试
   如果when语句块的末尾使用continue,perl就会尝试执行后续的when语句,意味着所有的条件判断都会执行
   given($ARGV[0]){
       when($_~~/fred/i){say 'Name has fred in it',continue}
       when($_~~/^Fred/){say 'Name starts with Fred',continue}
       when($_~~'Fred'){say 'Name is Fred',continue}
       default {say 'I don't see a Fred'}
    }
   如果不想必须执行default,可以将最后一个continue去掉
笨拙匹配:除了在given-when中使用智能匹配外,还可以像前面那样使用所谓笨拙匹配
   given($ARGV[0]){
       when($_=~/fred/i){say 'Name has fred in it',continue}
       when($_=~/^Fred/){say 'Name starts with Fred',continue}
       when($_=~'Fred'){say 'Name is Fred'}
       default {say 'I don't see a Fred'}
    }
   甚至可以混用笨拙匹配和智能匹配
多个项目的when匹配:有时候需要遍历许多元素,可given智能一次接受一个参数
   因此可以使用foreach简写方式,让它给当前正在遍历的元素起个化名$_
    foreach(@names){
       when(/fred/i){say 'Name has fred in it',continue}
       when(/^Fred/){say 'Name starts with Fred',continue}
       when('Fred'){say 'Name is Fred'}
       default {say 'I don't see a Fred'}
    }
   此外,若要用智能匹配,当前元素只能是$_
   另外,可以在when语句之间写上其他语句用于调试
    foreach(@names){
       say "\nProessing $_";
       when(/fred/i){say 'Name has fred in it',continue}
       when(/^Fred/){say 'Name starts with Fred',continue}
       when('Fred'){say 'Name is Fred'}
       say "Moving on to default...";
       default {say 'I don't see a Fred'}
      
0 0
原创粉丝点击