Perl比较两个文件并将行复制到新文件

Perl比较两个文件并将行复制到新文件,perl,Perl,我是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"); m

我是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;
使用严格;
使用警告;
打开(IDS,“>”,“outtest.txt”);
foreach$id(@metas){
打印输出1“$meta”。\n”;
}
关闭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
使用严格;
使用警告;
打开(META,“>”,“outtest.txt”);
打印输出1连接“\n”、@值#使用换行符联接并在输出文件中打印输出行。
关闭1#关闭打开的文件

在哪里匹配ID?你的问题是你想把那些“具有匹配ID”的文件放在另一个文件中,哪里有匹配?另外,
my$scalar=@array
将对@scalar的元素进行计数,并将结果存储在$scalar中。我不确定这是你想要的,但似乎以后也不会用,只是说……谢谢,@BytePasher和mpapec,你的评论对我很有启发!id.txt 1 2 3 4 6 meta.txt 1这是序列号1。2这是序列号2。3这是序列号3。4这是序列号4。6这是序列号4。非常感谢!你的回答很有帮助!