Read file into variable in Perl [duplicate]

a 夏天 提交于 2019-12-08 14:54:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!