+ -
当前位置:首页 → 问答吧 → 新手求助perl智能匹配

新手求助perl智能匹配

时间:2011-07-13

来源:互联网

my @nums = qw( 2  3  42 27 );
my $result = max( @nums );

sub max{
  my ($max_so_far) = shift @_;
  foreach( @_ ) {
  if ($_ > $max_so_far ){
   $max_so_far = $_;
   }
}
  return $max_so_far;
print "$max_so_far\n";
}
print "the values is existed\n" if $result ~~ @nums;

print "the values is existed\n" if @nums ~~ $result;
为什么按照第二个print语句写没有运行结果,第一个print的运行结果是对的;可书上说智能匹配对两边操作数的顺序没有要求。这两种写法应该有同样的运行结果才对,可实际结果不对。

还有我打印result的值的时候应该是42,怎么输出结果是1啊?

请高手帮忙!谢谢

作者: stesting   发布时间: 2011-07-13



QUOTE:
my @nums = qw( 2  3  42 27 );
my $result = max( @nums );

sub max{
  my ($max_so_far) = shift @_ ...
stesting 发表于 2011-07-13 14:39




    你的书过时了 可书上说智能匹配对两边操作数的顺序没有要求。 这一点 5.10.1 改变了

作者: zhlong8   发布时间: 2011-07-13

http://perldoc.perl.org/perlsyn.html#Switch-statements
往下稍微翻一点有个表,用 ~~ 要看这里



QUOTE:
    $a      $b        Type of Match Implied    Matching Code
    ======  =====     =====================    =============
    Any     undef     undefined                !defined $a
    Any     Object    invokes ~~ overloading on $object, or dies
    Hash    CodeRef   sub truth for each key[1] !grep { !$b->($_) } keys %$a
    Array   CodeRef   sub truth for each elt[1] !grep { !$b->($_) } @$a
    Any     CodeRef   scalar sub truth          $b->($a)
    Hash    Hash      hash keys identical (every key is found in both hashes)
    Array   Hash      hash keys intersection   grep { exists $b->{$_} } @$a
    Regex   Hash      hash key grep            grep /$a/, keys %$b
    undef   Hash      always false (undef can't be a key)
    Any     Hash      hash entry existence     exists $b->{$a}
    Hash    Array     hash keys intersection   grep { exists $a->{$_} } @$b
    Array   Array     arrays are comparable[2]
    Regex   Array     array grep               grep /$a/, @$b
    undef   Array     array contains undef     grep !defined, @$b
    Any     Array     match against an array element[3]
                                               grep $a ~~ $_, @$b
    Hash    Regex     hash key grep            grep /$b/, keys %$a
    Array   Regex     array grep               grep /$b/, @$a
    Any     Regex     pattern match            $a =~ /$b/
    Object  Any       invokes ~~ overloading on $object, or falls back:
    Any     Num       numeric equality         $a == $b
    Num     numish[4] numeric equality         $a == $b
    undef   Any       undefined                !defined($b)
    Any     Any       string equality          $a eq $b
1 - empty hashes or arrays will match.
2 - that is, each element smart-matches the element of same index in the
     other array. [3]
3 - If a circular reference is found, we fall back to referential equality.
4 - either a real number, or a string that looks like a number

作者: zhlong8   发布时间: 2011-07-13