Perl read file into a variable

— Read the contents into a scalar

The whole file is stored in a single scalar variable. To do this, the special variable $/ should have an undefined value when reading the file.

Here’s one way to do it:

open FILE, "<file.txt";
$file_contents = do { local $/; <FILE> };

When you need to process small files, it’s usually easier to read the whole file contents in a variable; here’s how to do it:

— Read the contents into an array

Each row will be stored in an array element:

open FILE, "<file.txt";
@lines = <FILE>;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s