在Perl中将文件读入变量 [英] Read file into variable in Perl
本文介绍了在Perl中将文件读入变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
什么是最好的在Perl中将文件插入字符串的方法?
Possible Duplicate:
What is the best way to slurp a file into a string in Perl?
此代码是将文件内容读入Perl中的变量的好方法吗?可以,但是我很好奇我是否应该使用更好的做法.
Is this code a good way to read the contents of a file into a variable in Perl? It works, but I'm curious if there is a better practice I should be using.
open INPUT, "input.txt";
undef $/;
$content = <INPUT>;
close INPUT;
$/ = "\n";
推荐答案
我认为通常的做法是这样的:
I think common practice is something like this:
my $content;
open(my $fh, '<', $filename) or die "cannot open file $filename";
{
local $/;
$content = <$fh>;
}
close($fh);
使用3个参数open
更安全.将文件句柄用作变量是在现代Perl中应如何使用它,而使用local $/
将在块末尾恢复$/
的初始值,而不是硬编码的\n
.
Using 3 argument open
is safer. Using file handle as variable is how it should be used in modern Perl and using local $/
restores initial value of $/
on block end, instead of your hardcoded \n
.
这篇关于在Perl中将文件读入变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文