一个perl的实验程序,模式匹配的应用

     1 #! /usr/bin/perl  -w
     2 my $t=open DATA,  "test.data";
     3 unless ($t)
     4 {
     5       print "can not open test.dat";
     6 }
     7 print "please input name you want to locat /n";
     8 $kk=<STDIN>;
     9 chomp $kk;
    10 if ($kk=~//s*(/w+/s*/w*)/s*/)
    11  {
    12   $kk=$1;
    13   print $kk,"/n";
    14  }
    15  
    16 while( $name=<DATA>)
    17  {
    18   chomp $name;
    19   if($name=~/(/w+/s*/w+)/s*:/s*(/w+/s*/w+)/s*/)
    20   {
    21      $label=$1;
    22    $info=$2;
    23   # print "the /$label $label/n";
    24   # print "the /$info  $info/n";
    25    if ($kk eq $info)
    26    {
    27     $k=1;
    28    }
    29    if (defined($k)and $k<5)
    30    { 
    31     print "the $label of $kk is :$info/n";
    32     $k+=1;
    33    }
    34   }
    35  }
    36 #function for chomp the /s at head and end of the word $word;
    37 sub abstract{
    38  foreach(@_)
    39  { 
    40   print "$_/n";
    41   if (//s*(/w+(/s*/w+)*)/)
    42   { 
    43    $1;
    44    printf "the word is :$1:/n";
    45   }
    46   else
    47   { 
    48    print "the $1/n";
    49    undef;
    50   }
    51  }
    52 }
    53 print "pleas input test data:string/n";
    54 chomp($var=<STDIN>);
    55 print "the result of abstact fun",abstract($var),"/n";
    56 
 以上程序实现了从文件 test.data中检索出用户制定的人的info

以下是test.data:

  name :  wangsheng
  age  : 20
gender: man;
  phone :123

name :ws
age  : 23
gender  : woman
phone :222

以上的输入文件中的数据有一个特点是它的数据比较凌乱,如在 name 的前后就有几空格。怎么处理这前后的空格

1)19   if($name=~/(/w+/s*/w+)/s*:/s*(/w+/s*/w+)/s*/)
    20   {
    21      $label=$1;
    22    $info=$2;
    23   # print "the /$label $label/n";
    24   # print "the /$info  $info/n";

 这种解决办法看似可以其实有Bug 对单字母就没办法了。

2) 37 sub abstract{
    38  foreach(@_)
    39  { 
    40   print "$_/n";
    41   if (//s*(/w+(/s*/w+)*)/)
    42   { 
    43    $1;
    44    printf "the word is :$1:/n";
    45   }
    46   else
    47   { 
    48    print "the $1/n";
    49    undef;
    50   }
这种解决方法就很好,(foreach 中的循环返回值时有问题,要改一改但思想没问题)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值