regex - 使用 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);
解决方案
您的输入文件之一是 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
或标准化是个好主意。||
推荐阅读
- python-3.x - NLP中列表或文件的单词总数(列表长度)与词汇表之间的差异?
- android - 如果我的应用程序之前处于草稿状态,是否可以上传针对新密钥库签名的新应用程序?
- javascript - react-loadable 组件不等待触发器加载
- python - 获取选定值的索引
- powerbi - 按月获取公开票
- javascript - 将 Typescript 中的函数传递给另一个函数时,如何设置该函数的类型?
- php - Add button is used to display dropdown and when select dropdown get displayed without null value then other dropdown should appear
- graph - 如何在tikz图片上的圆圈上方画一个数字?
- python-3.x - 我不断收到一个维度错误,它说它期望输入有 4 个维度,但形状为 (2062,64,64)。
- javascript - JS 导入更新的 JSON 文件以用于 ChartJS