Chinaunix首页 | 论坛 | 博客
  • 博客访问: 838243
  • 博文数量: 253
  • 博客积分: 6891
  • 博客等级: 准将
  • 技术积分: 2502
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-03 11:01
文章分类

全部博文(253)

文章存档

2016年(4)

2013年(3)

2012年(32)

2011年(184)

2010年(30)

分类: Python/Ruby

2011-10-17 10:31:03

The smart match operator, ~~, looks at both of its operands and decides on its own how it should compare them. If the operands look like numbers, it does a numeric comparison. If they look like strings, it does a string comparison. If one of the operands is a regular expression, it does a pattern match.
  1. print "I found Fred in the name!\n" if $name =~ /Fred/;
  2. the same with
  3. use 5.010;
  4. say "I found Fred in the name!" if $name ~~ /Fred/;
if we want to check if one of the keys in %hash matches "Fred", we cannot use exists(it will check the exact key). we can use the smart match operator.

  1. use 5.010;
  2. say "I found a key matching 'Fred'" if %names ~~ /Fred/;
The smart match operator knows what to do because it sees a hash and a regular ex-
pression. With those two operands, the smart match operator knows to look through
the keys in %names and apply the regular expression to each one. If it finds one that
matches, it already knows to stop and return true. It’s not the same sort of match as
the scalar and regular expression. It’s smart; it does what’s right for the situation. It’s
just that the operator is the same, even though the operation isn’t.

also use ~~ to compare two arrays.
  1. use 5.010;
  2. say "The arrays have the same elements!"
  3.     if @names1 ~~ @names2;
to check if the scalar in the array.

  1. use 5.010;
  2. my @nums = qw( 1 2 3 27 42 );
  3. my $result = max( @nums );
  4. say "The result [$result] is one of the input values (@nums)"
  5.     if @nums ~~ $result;
  6. You can also write that smart match with the operands in the other order and get the
  7. same answer. The smart match operator doesn’t care which operands are on which side:
  8. use 5.010;
  9. my @nums = qw( 1 2 3 27 42 );
  10. my $result = max( @nums );
  11. say "The result [$result] is one of the input values (@nums)"
  12.     if $result ~~ @nums;
Table 15-1. Smart match operations for pairs of operands
Example Type of match
%a ~~ %b Hash keys identical
%a ~~ @b At least one key in %a is in @b
%a ~~ /Fred/ At least one key matches pattern
%a ~~ 'Fred' Hash key existence exists $a{Fred}
  
@a ~~ @b Arrays are the same
@a ~~ /Fred/ At least one element matches pattern
@a ~~ 123 At least one element is 123, numerically
@a ~~ 'Fred' At least one element is 'Fred', stringwise
  
$name ~~ undef $name is not defined
$name ~~ /Fred/ Pattern match
123 ~~ '123.0' Numeric equality with “numish” string
'Fred' ~~ 'Fred' String equality
123 ~~ 456 Numeric equality
阅读(625) | 评论(0) | 转发(0) |
0

上一篇:sort hash

下一篇:given-when control structure

给主人留下些什么吧!~~