異なる種類の行末を持つ 2 つの非常に大きな XML ファイルがあります。ファイル A には、各 XML レコードの末尾に CR LF があります。ファイル B には、各 XML レコードの最後に CR しかありません。
ファイル B を正しく読み取るには、組み込みの Perl 変数 $/ を "\r" に設定する必要があります。しかし、ファイル A で同じスクリプトを使用している場合、スクリプトはファイルの各行を読み取るのではなく、1 行として読み取ります。
さまざまな行末区切り文字を持つテキスト ファイルと互換性のあるスクリプトを作成するにはどうすればよいですか? 以下のコードでは、スクリプトは XML データを読み取り、<\record> のような特定の XML タグ レコード終了タグに基づいて正規表現を使用してレコードを分割しています。最後に、要求されたレコードをファイルに書き込みます。
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;