Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read the contents of a small text file into a scalar in Perl?

Tags:

file-io

perl

I have a small text file that I'd like to read into a scalar variable exactly as it is in the file (preserving line separators and other whitespace).

The equivalent in Python would be something like

buffer = ""

try:
    file = open("fileName", 'rU')
    try:
        buffer += file.read()
    finally:
        file.close()
except IOError:
    buffer += "The file could not be opened."

This is for simply redisplaying the contents of the file on a web page, which is why my error message is going into my file buffer.

like image 491
Bill the Lizard Avatar asked Jan 28 '09 15:01

Bill the Lizard


4 Answers

From the Perl Cookbook:

my $filename = 'file.txt';
open( FILE, '<', $filename ) or die 'Could not open file:  ' . $!;

undef $/;
my $whole_file = <FILE>;

I would localize the changes though:

my $whole_file = '';
{
    local $/;
    $whole_file = <FILE>;
}
like image 134
gpojd Avatar answered Oct 04 '22 00:10

gpojd


As an alternative to what Alex said, you can install the File::Slurp module (cpan -i File::Slurp from the command line) and use this:

use File::Slurp;
# Read data into a variable
my $buffer = read_file("fileName");
# or read data into an array
my @buffer = read_file("fileName");

Note that this dies (well... croaks, but that's just the proper way to call die from a module) on errors, so you may need to run this in an eval block to catch any errors.

like image 41
Powerlord Avatar answered Oct 04 '22 00:10

Powerlord


If I don't have Slurp or Perl6::Slurp near by then I normally go with....

open my $fh, '<', 'file.txt' or die $!;

my $whole_file = do { local $/; <$fh> };
like image 24
draegtun Avatar answered Oct 03 '22 23:10

draegtun


There is a discussion of the various ways to read a file here.

like image 41
drby Avatar answered Oct 04 '22 00:10

drby