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 中的循环返回值时有问题,要改一改但思想没问题)