【问题标题】:Perl compare two files and copy lines to new filePerl比较两个文件并将行复制到新文件
【发布时间】:2014-11-27 14:39:45
【问题描述】:

我是 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;

【问题讨论】:

  • 您在哪里匹配 ID?你的问题是说你想要那些在另一个文件中“具有匹配 ID”的文件,哪里有任何匹配?此外,my $scalar = @array; 将计算 @scalar 的元素并将结果存储在 $scalar 中。不知道是不是你想要的,不过后面好像也没怎么用,只是说……
  • 谢谢@bytepusher 和mpapec,你们的cmets 对我很有启发!

标签: perl


【解决方案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

【讨论】:

  • id.txt 123456 meta.txt 1这是序号是1。2这是序号number 是 2。3这是序号是 3。4这是序号是 4。 6这是序号是4。
  • 非常感谢!你的回答很有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-14
  • 2022-08-21
  • 2015-07-08
  • 1970-01-01
  • 2018-08-17
相关资源
最近更新 更多