一个Perl文本处理实例

来源:互联网 发布:何不食肉糜现代版知乎 编辑:程序博客网 时间:2024/05/19 05:03
假设存在file1, file2两个文本文件, 文件每行格式为:
| .* | .*;
要求:求出所有在file2文件中出现的行, 且仅保留双"|"之间的内容。
如: 若存在 |adfdf| dofijaosdjioaf 于file2, file1中不存在该项,则该返回 |adfdf|

参考例程:
#!/usr/bin/perl
use strict;
use warnings;

die "lack compare file/n" if(@ARGV < 2);
my ($file1, $file2) = ($ARGV[0], $ARGV[1]);
my $outfile = "result.out"; # storage result

#-------- format the input file into like this :  |.*|
$^I = ".bak";   # make a copy
while(<>)
{
   s/[^|]*$//;
   print;
   print "/n";
}
#-----------

system "diff $file1 $file2 > temp.out";
open TEMP, "<temp.out" or die "Can not open temporary file/n";
open OUT, ">$outfile" or die "Can not open file:$outfile/n";

my $count=0;
while(<TEMP>)
{
        chomp;
        if(//>(.*)/)
        {
            $count++;
            print OUT "$1/n";
        }
}
print OUT "total sums = $count/n";
close TEMP;
unlink "temp.out";
close OUT;
原创粉丝点击