将文件读入Perl中的变量

itz*_*tzy 14 perl slurp filehandle

可能重复:
在Perl中将文件粘贴到字符串中的最佳方法是什么?

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

open INPUT, "input.txt";
undef $/;
$content = <INPUT>;
close INPUT;
$/ = "\n";
Run Code Online (Sandbox Code Playgroud)

n0r*_*0rd 30

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

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

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


Que*_*tin 15

use File::Slurp;
my $content = read_file( 'input.txt' ) ;
Run Code Online (Sandbox Code Playgroud)

  • 我不同意在一个加上一个模块的情况下不断地一遍又一遍地编写相同的五行代码. (17认同)
  • 无论你生成Makefiles的是什么依赖都是为了. (5认同)
  • 它甚至不是标准模块.这降低了代码的可移植性. (4认同)
  • 我不同意加载模块只是为了打开和读取文件.能够打开和读取文件是非常基本的操作,不能非常,非常好地理解. (2认同)