Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file into variable in Perl [duplicate]

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";
like image 891
itzy Avatar asked Nov 03 '10 13:11

itzy


People also ask

How do I read an entire file in a variable in Perl?

use File::Slurp; my $file_content = read_file('text_document. txt'); File::Slurp's read_file function to reads the entire contents of a file with the file name and returns it as a string. It's simple and usually does what it's expected to do.

What is $@ in Perl?

$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.

How do I store contents to a variable in Perl?

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 .

What is $_ in Perl script?

The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }


3 Answers

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.

like image 102
n0rd Avatar answered Oct 30 '22 12:10

n0rd


use File::Slurp;
my $content = read_file( 'input.txt' ) ;
like image 20
Quentin Avatar answered Oct 30 '22 14:10

Quentin


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.

like image 35
Daniel Martin Avatar answered Oct 30 '22 14:10

Daniel Martin