首页 > 解决方案 > 使用 perl 处理名称和详细信息列表

问题描述

有两个文件。一个文件是名称列表。另一个文件是名称和详细信息的列表。我想创建第三个文件,其中包含来自第一个文件的名称和来自第二个文件的详细信息(该名称的)。你能建议一下吗?

第二个文件的详细信息由模式“list[i]”(来自第一个文件的名称)和“</reg>”分隔

#!/usr/intel/bin/perl


use warnings;
use strict;
use Data::Dumper;



my $handle;
unless (open $handle, "<:encoding(utf8)", "/nfs/fm/disks/fm_nvm_7138/WLRD_LOGIC_users/cgoudarx/willard_b02/chiplevel/verif/testsuites/upf/pss_ret_regs.txt") {
   print STDERR "Could not open file '/nfs/fm/disks/fm_nvm_7138/WLRD_LOGIC_users/cgoudarx/willard_b02/chiplevel/verif/testsuites/upf/pss_ret_regs.txt': $!\n";
   # we return 'undefined', we could also 'die' or 'croak'
   return undef
}
chomp(my @list = <$handle>);
unless (close $handle) {
   # what does it mean if close yields an error and you are just reading?
   print STDERR "Don't care error while closing '/nfs/fm/disks/fm_nvm_7138/WLRD_LOGIC_users/cgoudarx/willard_b02/chiplevel/verif/testsuites/upf/pss_ret_regs.txt': $!\n";
} 

open ( INPUT, "/nfs/fm/disks/fm_nvm_7138/WLRD_LOGIC_users/cgoudarx/willard_b02/chiplevel/verif/testsuites/upf/tet.xml" ) or die("Could not open xml file.");

my $outffile ="newlist.xml";
open(FILEOUT2, ">$outffile") || die "ERROR: Can't open the output file $outffile: $!";

my $size = @list;

for (my $i=0; $i < $size; $i++) {
    while( my $line = <INPUT> )
    {

        if ( $line =~ m/$list[$i]/) {
            print FILEOUT2 $line;
            while( $line = <INPUT>) # print till empty line
            {
                last if ( $line =~ m/<\/reg>/);
                print FILEOUT2 $line;
            }
            print FILEOUT2 $line;
        };
    };
};

close(INPUT);

标签: regexfileperl

解决方案


您的输入文件之一是 XML 文档。您不应该使用正则表达式解析 XML 文档。使用适当的 XML 解析器(我推荐XML::LibXML)是一个更好的主意。

如果您坚持使用正则表达式解析 XML,那么您不能一次处理一行输入文件,因为 XML 元素通常(通常?)跨越多行。

另外,请更新您的文件处理代码以使用三参数版本open()和词法文件句柄。

open ( my $in_fh, '<', "...") or die("Could not open xml file.");

open( my $out_fh, '>', $outffile) || die "ERROR: Can't open the output file $outffile: $!";

哦,在这些命令中使用or或标准化是个好主意。||


推荐阅读