两个Perl数组的常见元素

Mar*_*ary 0 perl

可能重复:
使用Perl比较两个数组

我试图找到两个文件中常见的元素:下面是我的代码.请告诉我我在做什么错.

open IN,  "New_CLDB.txt"     or die "couldn't locate input file";
open IN1, "New_adherent.txt" or die "couldn't locate input file";
use Data::Dumper;
@array = ();
while (<IN>) {
    $line = $_;
    chomp $line;
    $a[$i] = $line;
    ++$i;
}
while (<IN1>) {
    $line1 = $_;
    chomp $line1;
    $b[$m] = $line1;
    ++$m;
}
for ( $k = 0; $k < $i; ++$k ) {
    for ( $f = 0; $f < $m; ++$f ) {
        if ( $a[$k] ne $b[$f] ) {
            push( @array, $a[$k] );
        }
    }
}
print @array, "\n";
Run Code Online (Sandbox Code Playgroud)

Lum*_*umi 6

请告诉我我在做什么错.

从表面上看你的代码,这是一个列表:

  • 不使用strictpragma
  • 没有你想要达到的精确规格
  • 试图立刻做太多

离开代码一步,用简单的英语思考它.你需要做什么?

  • 读取文件 - 打开,读取,关闭
  • 将文件数据读入数组 - 究竟如何?
  • 使用函数不要为文件A和文件B重复自己
  • 比较数组

独立完成每项任务,始终使用strict.总是.然后才将单个步骤组成一个更大的脚本.

你也可以看看这个其他的SO问题.