问题
Possible Duplicate:
What is the best way to slurp a file into a string in 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";
回答1:
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);
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
.
回答2:
use File::Slurp;
my $content = read_file( 'input.txt' ) ;
回答3:
Note that if you're in an environment where installing modules is possible, you may want to use IO::All:
use IO::All;
my $contents;
io('file.txt') > $contents;
Some of the possibilities get a bit crazy, but they can also be quite useful.
来源:https://stackoverflow.com/questions/4087743/read-file-into-variable-in-perl