Passing entire file to a variable in a single command

S

solutions

Hi,

I was wondering if anyone knows how to pass the contents of an entire
file to a variable IN A SINGLE LINE/COMMAND? It's trivial to do with a
few lines, but I am wondering if there is a more clever way to do this.

my $file_text = some_command( filehandle ) ???

Thanks,
David
 
A

A. Sinan Unur

(e-mail address removed) wrote in
I was wondering if anyone knows how to pass the contents of an entire
file to a variable IN A SINGLE LINE/COMMAND? It's trivial to do with a
few lines, but I am wondering if there is a more clever way to do
this.

That is called slurping a file.
my $file_text = some_command( filehandle ) ???

One way of doing that is:

#!/usr/bin/perl

use strict;
use warnings;

open my $in, '<', 'ttt.pl'
or die "Cannot open ttt.pl: $!";

my $text = do { local $/; <$in> };

print $text;

__END__

For details, see perldoc perlvar, and read about $/

These days, I prefer using File::Slurp by Uri Guttman
(we miss you Uri :)

You can find it on CPAN.

Sinan
 
G

Gunnar Hjalmarsson

I was wondering if anyone knows how to pass the contents of an entire
file to a variable IN A SINGLE LINE/COMMAND?

my $file_text = do { undef $/; <FH> };
 
G

Gunnar Hjalmarsson

Gunnar said:
my $file_text = do { undef $/; <FH> };
---------------------------^^^^^

Oops, please disregard my reply; Sinan showed how it can be done.
 
G

Gunnar Hjalmarsson

Gunnar said:
--------------------------^^^^^

Oops, please disregard my reply; Sinan showed how it can be done.

Since the above code also 'works', I thoght I'd say *why* (I think) it's
not good.

Just saying undef $/ affects the value of $/ globally, which may cause
surprises later on in the program. The whole point with using a block is
to limit this value of the $/ variable to the block, which you do by
instead saying

my $file_text = do { local $/; <FH> };
-------------------------^^^^^

Hopefully my explanation was not as bad as the first suggestion. ;-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top