itz*_*tzy 14 perl slurp filehandle
这段代码是将文件内容读入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)