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";
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.
$@ 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.
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 .
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"; }
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
.
use File::Slurp;
my $content = read_file( 'input.txt' ) ;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With