【问题标题】:Holding files in memory in perl while using them like file handles在 perl 中将文件保存在内存中,同时像文件句柄一样使用它们
【发布时间】:2015-03-05 04:26:18
【问题描述】:

我有一个需要修改的 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);

如果文件大小

【问题讨论】:

  • 是的,有可能。
  • 不错!这怎么可能?
  • 您可以使用 Number::Bytes::Human::sizeDevel::Size::size 测试可以在内存中存储多大的字符串:在我的笔记本电脑上,我可以达到大约 4 GB... 例如:print format_bytes(size("1" x 3_100_000_000)) . "\n"; 给出 2.9 G..
  • 我也获得了 2.9 GB。我认为内存缓冲区还可以,只是将其用作失败的文件句柄。

标签: perl file io


【解决方案1】:

读入文件:

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

并打开它的文件句柄:

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

【讨论】:

  • 要使代码向后兼容 5.8 之前的 Perl,请使用 IO::String module..
  • 所以原则上这对我有用,但不幸的是它不适用于大文件(>2 GB)。在这种情况下,$file_contents 保存文件的内容,但 返回一个空变量。有没有办法解决这个问题?
猜你喜欢
  • 2015-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-30
  • 2015-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多