将文件读入Perl中的变量

时间:2010-11-03 13:57:25

标签: perl filehandle slurp

  

可能重复:
  What is the best way to slurp a file into a string in Perl?

这段代码是将文件内容读入Perl变量的好方法吗?它有效,但我很好奇我是否应该使用更好的练习。

open INPUT, "input.txt";
undef $/;
$content = <INPUT>;
close INPUT;
$/ = "\n";

3 个答案:

答案 0 :(得分:29)

我认为通常的做法是这样的:

    my $content;
    open(my $fh, '<', $filename) or die "cannot open file $filename";
    {
        local $/;
        $content = <$fh>;
    }
    close($fh);

使用3个参数open更安全。使用文件句柄作为变量是如何在现代Perl中使用它并使用local $/在块结束时恢复$/的初始值,而不是使用硬编码的\n

答案 1 :(得分:15)

use File::Slurp;
my $content = read_file( 'input.txt' ) ;

答案 2 :(得分:2)

请注意,如果您处于可以安装模块的环境中,则可能需要使用IO::All

use IO::All;
my $contents;
io('file.txt') > $contents;

有些可能性有点疯狂,但它们也非常有用。