在perl中保存内存中的文件,同时像文件句柄一样使用它们



我有一个perl脚本需要修改。该脚本打开、读取和查找两个大型 (ASCII) 文件(它们的大小为几 GB)。由于它做了很多,我想将这两个文件完全放入 RAM 中。在不大量修改脚本的情况下执行此操作的最简单方法是将文件加载到内存中,以便我可以将结果变量视为文件句柄 - 例如使用 seek 到达特定的字节位置。这在 perl 中可能吗?

更新:按照建议使用 File::Slurp 仅对小文件完成工作。如果文件大于大约 2GB,则不起作用。

最小示例:

#!/usr/bin/env perl
use strict;
use warnings;
use Tie::File;
use File::Slurp 'read_file';
my $fn="testfile";
#buffer, then open as file, read first line:
read_file($fn, buf_ref => my $file_contents_forests) or die "Could not read file!";
my $filehandle;
open($filehandle, "<", $file_contents_forests) or die "Could not open buffer: $!n";
my $line = "the first line:".<$filehandle>;
print $line."n";
close($filehandle);
#open as file, read first line:
open( FORESTS,  "<",$fn) or die "Could not open file.n";
my $line = "the first line:".<FORESTS>;
print $line;
close(FORESTS);

如果文件大小<2 GB,则这两种方法在这种情况下的输出是相同的。如果文件较大,则 slurping 返回一个空行。

在文件中读取:

use File::Slurp 'read_file';
read_file( "filename", buf_ref => my $file_contents );

并打开它的文件句柄:

open my $file_handle, '<', $file_contents;

最新更新