sub readfile{ my(@tmp)=@_; my($line); open (MYFILE, $tmp[0]) || die ("Could not open file"); while ($line=<MYFILE>) { print $line; } }
sub checkfile{ my(@tmp)=@_; open (MYFILE, $tmp[0]) || die ("Could not open file"); my($line,$pattern,$lamp); $pattern=$tmp[1]; $lamp=0; while (chomp($line=<MYFILE>)) { if($line!~/$pattern/) { print "[$line ] :this line is wrong formatn"; $lamp=1; } } if($lamp) { print "n",$tmp[2],"n";}
close(MYFILE); }
sub gotest{ my(@tmp)=@_;
open (MYFILE, $tmp[0]) || die ("Could not open file"); my($line,$newline); while ($line=<MYFILE>) { $line=~ tr/a-zA-Z//s; print "good n"; print "$line is :$line"; print "$& is : $&", "n"; }
close(MYFILE); }
文件结束要return 1;
1;
如何使用模块
模块文件必须先cp到perl的库目录下,才能被use
[macg@localhost perltest]$ ls testdir file1.pl file1.pm test1 [macg@localhost perltest]$ su Password: [root@localhost perltest]# cp testdir/file1.pm /usr/lib/perl5/5.8.6/
[root@localhost perltest]# exit exit
在perl编程中使用模块
[macg@localhost perltest]$ vi tip.pl #!/usr/bin/perl use file1; use 模块
[macg@localhost perltest]$ ./tip.pl host1 202.106.0.20 host2 9.89.9.1 host3 10.0.23.6 11.0.25.9 host5 12.0.1.0as ----------------------------------------- [11.0.25.9 ] :this line is wrong format [host5 12.0.1.0as ] :this line is wrong format
example:hostname1 10.10.20.2
.pm文件不仅放在perl工作库目录,其实放在当前目录,也可以直接use
vi tip.pl #!/usr/bin/perl package main; use file1;
[root@localhost perltest]# rm /usr/lib/perl5/5.8.6/file1.pm rm: remove regular file `/usr/lib/perl5/5.8.6/file1.pm'? y
[macg@localhost perltest]$ ls 当前目录中 file1.pm gogo newdir newtest test testdir tip.pl