perl比较两个文件字符串的实例代码
程序员文章站
2022-07-11 15:17:07
需求:取文件1中的一行,和文件2中所有的数据进行比较,有相同的保存起来,否则删除。复制代码 代码如下:#!/usr/bin/perl#use strict;open(fil...
需求:取文件1中的一行,和文件2中所有的数据进行比较,有相同的保存起来,否则删除。
#!/usr/bin/perl
#use strict;
open(file1,"c:/perl/bx/bx-users.txt");
open(file2,"c:/perl/bx/bx-book-ratings.txt");
open(result1,">c:/perl/bx/bx-users_result.txt");
my $i=0;
my $j=0;
while((my $bxuser=<file1>)&&($i<10))
{
my $userid=substr($bxuser,0,index($bxuser,","));
while(my $rankuser=<file2>)
{
my $useridcmp=substr($rankuser,0,index($rankuser,","));
if(($userid==$useridcmp)&&($j==0))
{
syswrite(result1,"$bxuser");
$j++;
}
}
$j=0;
$i++;
}
close(file1);
close(file2);
close(result1);
复制代码 代码如下:
#!/usr/bin/perl
#use strict;
open(file1,"c:/perl/bx/bx-users.txt");
open(file2,"c:/perl/bx/bx-book-ratings.txt");
open(result1,">c:/perl/bx/bx-users_result.txt");
my $i=0;
my $j=0;
while((my $bxuser=<file1>)&&($i<10))
{
my $userid=substr($bxuser,0,index($bxuser,","));
while(my $rankuser=<file2>)
{
my $useridcmp=substr($rankuser,0,index($rankuser,","));
if(($userid==$useridcmp)&&($j==0))
{
syswrite(result1,"$bxuser");
$j++;
}
}
$j=0;
$i++;
}
close(file1);
close(file2);
close(result1);