从现在开始,每天一点点……

智能匹配--given-when结构-------perl基础

上一篇 / 下一篇  2011-07-12 16:03:12 / 个人分类:perl基础

1.智能匹配操作符~~
  新的智能匹配操作符会根据需要自己决定用何种方式比较两端的操作数

下面这两段程序具有相同的效果
写法一:
my @name1 = / 1 2 3 4/;
my @name2 = /1 2 3 4 /;
my $equal = 0;
foreach my $index ( 0..$#name1){
last unless $name1[$index] eq $name2[$index];
$equal++;
print "$equal";
}
print "the arrays have the same element.\n" if $equal == @name1;

写法二:

my @name1 = / 1 2 3 4/;
my @name2 = /1 2 3 4 /;
say "the arays have the same element.\n" if @name1 ~~ @name2;

下面的例子是:在调用某个函数后,检查它的返回结果是否在某个集合中存在的两种写法.
写法一:
my @nums = qw( 2 3  42 27);
my $result = max( @nums );
my $flag = 0;

sub max{
  my ($max_so_far) = shift @_;
  foreach( @_ ) {
  if ($_ > $max_so_far ){
    $max_so_far = $_;
   }
 }
  return $max_so_far;
 #print "$max_so_far\n";
}

foreach my $num ( @nums ){
   next unless $result == $num;
   $flag = 1;
   #print "$flag\n";
   last;
}
print "the value is existed.\n" if $flag;


写法二:
my @nums = qw( 2 3  42 27 );
my $result = max( @nums );
say "$result\n";
sub max{
  my ($max_so_far) = shift @_;
  foreach( @_ ) {
  if ($_ > $max_so_far ){
   $max_so_far = $_;
   }
 }
  return $max_so_far;
}
print "the values is existed\n" if $result ~~ @nums;

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

2.智能匹配操作的优先级
例子                            匹配方式
%a ~~ %b                     哈希键是否一致
%a ~~ @b                  至少%a中的一个键在列表@b中
%a ~~ /fred/              至少一个键匹配给定的模式
%a ~~ 'fred'              哈希中某一指定键$a{fred}是否存在
 
@a ~~ @b                  数组是否相同
@a ~~ /fred/              有一个元素匹配给定的模式
@a ~~ 123                 至少有一个元素转化位数字后123
@a ~~ 'fred'              至少有一个元素转化为字符串后是 'fred'

$name ~~ undef            $name确实尚未定义
$name ~~ /fred/           模式匹配
123 ~~ '123.0'            数字和字符串是否大小相等
'fred' ~~ 'fred'          字符串是否完全相同
123 ~~ 456                 是否大小相等

3.given基本语句,given会将参数化名为$_,每个when条件测试都会尝试用智能匹配对$_进行测试。
use 5.010
given( $ARGV[0] ){
  when ( /fred/i ) { say 'Name has fred in it' }
  when ( /^fred/ ) { say 'Name start with fred'}
  when ( 'Fred' )  { say 'Name is Fred' }
  default          { say "I don't see a Fred" }
}

Continue的用法:

given( $array[0] ){
  when ( /fred/i ){ say 'name has fred in it';continue }
  when ( /^fred/ ){ say 'name start with fred';continue }
  when ( 'Fred' ) { say 'name is Fred' }
  default         { say "i don't see a Fred" }

}

4.多个项目的when匹配
  要遍历多个元素,就不用given,使用foreach的简写方式让他给当前正在遍历的元素起个化名$_,此外,若要使用智能匹配,当前元素就只能是$_.

#!/usr/bin/perl;
use 5.010;
my @array = qw/ Fred is good /;
foreach (@array) {
  when ( /fred/i ){ say 'name has fred in it';continue }
  when ( /^fred/ ){ say 'name start with fred';continue }
  when ( 'Fred' ) { say 'name is Fred' }
  default         { say "i don't see a Fred" }

}
运行结果如下:
name has fred in it
name is Fred
i don't see a Fred
i don't see a Fred




TAG:

 

评分:0

我来说两句

Open Toolbar