来自两个Perl数组的公共元素
可能重复:来自两个Perl数组的公共元素,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 = $_; ch
我试图找到两个文件中的共同元素: 下面是我的代码。请告诉我我犯了什么错误
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";
在“New_CLDB.txt”或“die”中打开“找不到输入文件”;
打开IN1,“New_appendent.txt”或die“找不到输入文件”;
使用数据::转储程序;
@数组=();
而(){
$line=$\;
chomp$行;
$a[$i]=$line;
++$i;
}
而(){
$line1=$\u1;
chomp$line1;
$b[$m]=$line1;
++百万美元;
}
对于($k=0;$k<$i;++$k){
对于($f=0;$f<$m;++$f){
如果($a[$k]ne$b[$f]){
推送(@array,$a[$k]);
}
}
}
打印@array,“\n”;
请告诉我我犯了什么错误
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";
从表面上看你的代码,这里有一个列表:
- 不使用
pragmastrict
- 没有一个你想要实现的精确规格
- 试图一下子做太多的事
- 读取文件-打开、读取、关闭
- 将文件数据读取到数组中-准确程度如何
- 对文件a和文件B使用一个不重复的函数
- 比较数组
strict
。总是。只有这样,才能将单个步骤组合成更大的脚本
您还可以看看。有几件事需要改进:
严格使用代码>和使用警告代码>
open
push@array$value追加一个数组代码>
对于如此多的问题。。。您的问题到底是什么?您希望得到什么。如果第二组中没有重复项:
my %set1;
while (<$fh1>) {
chomp;
++$set1{$_};
}
while (<$fh2>) {
chomp;
print("$_ is common to both sets\n")
if $set1{$_};
}
my %set1;
while (<$fh1>) {
chomp;
++$set1{$_};
}
my %set2;
while (<$fh2>) {
chomp;
print("$_ is common to both sets\n")
if $set1{$_} && !$set2{$_}++;
}
my%set1;
而(){
咀嚼;
++$set1{$};
}
而(){
咀嚼;
打印($对两个集合都是公共的\n)
如果$set1{$};
}
如果第二组中可能存在重复项:
my %set1;
while (<$fh1>) {
chomp;
++$set1{$_};
}
while (<$fh2>) {
chomp;
print("$_ is common to both sets\n")
if $set1{$_};
}
my %set1;
while (<$fh1>) {
chomp;
++$set1{$_};
}
my %set2;
while (<$fh2>) {
chomp;
print("$_ is common to both sets\n")
if $set1{$_} && !$set2{$_}++;
}
my%set1;
而(){
咀嚼;
++$set1{$};
}
我的%set2;
而(){
咀嚼;
打印($对两个集合都是公共的\n)
如果$set1{$\u}&!$set2{$\u}++;
}
@zidgon:它打印的值是无限的。仅供参考,两个文件都有一个列表请参见,,,,您正在测试字符串不平等性(ne
),当您需要相等性(eq
)时,请更改该列表,并在使用last
推送后中断内部循环,您的代码将仅打印公共元素。要想找到更完美的解决方案,请看ikegami的答案。为什么要投否决票?没有评论?也许是因为OP可以解决所有这些问题,但仍然无法回答她的问题。