我有两个非常大的XML文件,它们有不同的行结尾。 文件A在每个XML记录的末尾有CR LF。文件B在每个XML记录的末尾只有CR。如何使用不同的行分隔符读取大文件?
为了正确读取文件B,我需要将内置Perl变量$ /设置为“\ r”。 但是,如果我使用与文件A相同的脚本,脚本不会读取文件中的每一行,而是将其作为单行读取。
如何使脚本与具有各种行结束分隔符的文本文件兼容?在下面的代码中,脚本正在读取XML数据,然后使用正则表达式根据特定XML标记记录结束标记(如< \ record>)拆分记录。最后它将请求的记录写入文件。
open my $file_handle, '+<', $inputFile or die $!;
local $/ = "\r";
while(my $line = <$file_handle>) { #read file line-by-line. Does not load whole file into memory.
$current_line = $line;
if ($spliceAmount > $recordCounter) { #if the splice amount hasn't been reached yet
push (@setofRecords,$current_line); #start adding each line to the set of records array
if ($current_line =~ m|$recordSeparator|) { #check for the node to splice on
$recordCounter ++; #if the record separator was found (end of that record) then increment the record counter
}
}
#don't close the file because we need to read the last line
}
$current_line =~/(\<\/\w+\>$)/;
$endTag = $1;
print "\n\n";
print "End Tag: $endTag \n\n";
close $file_handle;
由于您认为XML文件在合理的位置甚至存在换行符,您将受到惩罚。 –
这意味着要分发,所以我不想用模块来解决这个问题。这是否意味着我不得不重新编写Perl以外的其他语言,以便更好地支持XML解析? – astra