+ -
当前位置:首页 → 问答吧 → 小骆驼疑问2

小骆驼疑问2

时间:2011-03-03

来源:互联网

书上提到智能匹配操作符,在应用:元素是否包含在数组里的时候,左右操作数顺序无所谓:

say "the result [$result] is one of the input values (@nums)" if @nums~~$result;
但是我运行上面,无法打印结果;
但是反过来:
say "the result [$result] is one of the input values (@nums)" if $result~~@nums;
反而能打印,不知道是怎么回事,具体代码如下:

#!/usr/bin/perl
use strict;
use 5.010;

my @nums=qw/1 2 300 27 42 22 2/;
my $result=max(@nums);
say "$result";
say "the result [$result] is one of the input values (@nums)" if $result~~@nums;
say "$result";

sub max{
my $bigone=shift @_;
foreach(@_){
        $bigone=$_ if $bigone<$_ ;
}
$bigone;
}

作者: alfred1980   发布时间: 2011-03-03

perlsyn 有个 smart match 的表格,貌似没有 Array ~~ Any 这项

作者: zhlong8   发布时间: 2011-03-03

难道有
any~~array?
那这样书上说的不是有问题?

作者: alfred1980   发布时间: 2011-03-03

一切以官方文档为准啊,书总会过时也有可能有错误
5.12 的文档中


QUOTE:
Any     Array     match against an array element[3]
                                               grep $a ~~ $_, @$b


http://perldoc.perl.org/perlsyn.html#Switch-statements 往下一点就是那个表

作者: zhlong8   发布时间: 2011-03-03

回复 alfred1980

Perl 5 最初引入 smart match  的时候(5.10.0 版),操作对象是可以互换的,但是从 5.10.1 版开始就是不可互换的了,互换的结果就可能完全不一样了。这个在 perldelta 里有说明的。

作者: Monox   发布时间: 2011-03-03

那天写了一个程序, 也被书上的智能匹配搞晕了。  调试了半天,变量位置一换就对了。

作者: justqb   发布时间: 2011-03-03