使用perl进行模式匹配
我有两个文件 在第一个文件的多行中有关键字要在第二个文件的多行中匹配。我需要获得这些关键字的计数 我创建的关键字,例如:使用perl进行模式匹配,perl,Perl,我有两个文件 在第一个文件的多行中有关键字要在第二个文件的多行中匹配。我需要获得这些关键字的计数 我创建的关键字,例如: ^.*\aB.c_Feg.*_vbn.*/ds_.*$ (^ and $ to indicate the beginning and end of line) 第二个文件中的行例如: P_csd.\[0] .i\-_\aB.c_Feg_90rAs (A#_vbn_T:) _345[/ds_] Asd_[0][7] 我写的代码是 #!/usr/bin/perl $file
^.*\aB.c_Feg.*_vbn.*/ds_.*$ (^ and $ to indicate the beginning and end of line)
第二个文件中的行例如:
P_csd.\[0] .i\-_\aB.c_Feg_90rAs (A#_vbn_T:) _345[/ds_] Asd_[0][7]
我写的代码是
#!/usr/bin/perl
$file= "$ARGV[0]";
open($File, '<', $file) or die "Can open '$file' for read: $!";
while ($var = <$File>)
{
push (@lines, $var);
}
$size = @lines;
$file1= "$ARGV[1]";
open($File1, '<', $file1) or die "Can open '$file1' for read: $!";
while ($var1 = <$File1>)
{
push (@lines1, $var1);
}
$size1 = @lines1;
$i = 0;
$j = 0;
$count=0;
for ( $i=0; $i<=$size; $i++)
{
while ( $j<=$size1)
{
if ($lines[$i] == $lines1[$j])
{
$count++;
$j++;
}
else
{
$j++;
}
}
print "$lines[$i] = $count\n";
$count = 0;
}
#/usr/bin/perl
$file=“$ARGV[0]”;
打开($File,首先,始终在脚本顶部“使用strict;使用warnings;”。这将捕获很多问题
看起来您正在对循环使用c-style,但不要将内部循环重置为0,因此它只会对整个第二个文件检查第一个关键字。此外,您正在使用numeric==来比较字符串。相反,您应该使用“eq”来比较字符串。在脚本顶部添加“use warnings;”将为字符串打印一条警告消息这类问题
您可以使用perlish表单并避免使用索引:
chomp @lines; # remove line endings
chomp @lines1;
for my $kw(@lines){
my $count = 0;
for my $text(@lines1){
$count ++ if $kw eq $text;
}
print "$kw = $count\n";
}
希望这有帮助。你得到了什么输出?缩进不仅仅是一个选项,而且是一个尊重的标记。第一个关键字我得到了一些值,但数组中剩余的关键字我得到了0。最后一个关键字我得到了like关键字=0while($var1=){push(@lines1,$var1);}
通常写为@lines1=
chomp @lines; # remove line endings
chomp @lines1;
for my $kw(@lines){
my $count = 0;
for my $text(@lines1){
$count ++ if $kw eq $text;
}
print "$kw = $count\n";
}