我是perl的初学者,我正在尝试用perl比较两个文件。一个包含id的列表,另一个包含包含id和更多文本的字符串。我想将具有匹配id的行复制到第三个文件,但是我只得到一个数字而不是正确的字符串。我做错了什么?
use strict;
use warnings;
open ( IDS , "<id.txt");
my @ids = <IDS>;
chomp(@ids);
close IDS;
my $id = @ids;
open ( META , "<meta.txt");
my @metas = <META>;
chomp(@metas);
my $meta = @metas;
open ( OUT1, ">>", "outtest.txt");
foreach $id (@metas){
print OUT1 "$meta"."\n";
}
close OUT1;
close META;
答案 0 :(得分:1)
尝试使用哈希变量来获取输出:
use strict;
use warnings;
open ( META , "<meta.txt");
my %idsValues = (); #Create one new HASH Variable
while(<META>)
{
my $line = $_;
if($line=~m{<id>(\d+)</id>\s*<string>([^<>]*)</string>})
{
$idsValues{$1} = $2; #Store the values and text into the HASH Variable
}
}
close(META); #Close the opened file
my @Values;
open ( IDS , "<id.txt");
while(<IDS>)
{
my $line = $_;
if($line=~m/<id>(\d+)<\/id>/i)
{
#Check if the value presents in the file and push them into ARRAY Variable.
push(@Values, "IDS: $1\tVALUES: $idsValues{$1}") if(defined $idsValues{$1} );
}
}
close(IDS); #Close the opened file
open ( OUT1, ">>", "outtest.txt");
print OUT1 join "\n", @Values; #Join with newline and Print the output line in the output file.
close OUT1; #Close the opened file