2013-06-03 66 views
1

我有两个非常大的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; 
+0

由于您认为XML文件在合理的位置甚至存在换行符,您将受到惩罚。 –

+0

这意味着要分发,所以我不想用模块来解决这个问题。这是否意味着我不得不重新编写Perl以外的其他语言,以便更好地支持XML解析? – astra

回答

0

如果文件不是太大的内存来保存,可以啜了整个事情变成一个标量,它自己与合适的柔性正则表达式拆分为正确的线路。例如,

local $/ = undef; 
my $data = <$file_handle>; 
my @lines = split /(?>\r\n)|(?>\r)|(?>\n)/, $data; 
foreach my $line (@lines) { 
    ... 
} 

使用前瞻断言(?>...)保存结束行的字符,例如定期<>操作一样。如果你只是想叮them他们,你可以通过/\r\n|\r|\n/来代替split来节省一步。

1

尽管您可能不需要它,理论上来说,要解析.xml,您应该使用xml解析器。我推荐XML::LibXM或者也许从XML::Simple开始。

+0

是的我可以使用它,但这个脚本是为了共享,我宁愿不需要其他人下载模块来运行它。 – astra

相关问题