Perl – How to Read a Text File into a Variable – 6 ways to do it

6 Ways to Read a Text File into a Variable

If you are working with large file(s) you might consider using File::Slurp.
It is much fast than the conventional:

{
  local $/=undef;
  open FILE, "myfile" or die "Couldn't open file: $!";
  binmode FILE;
  $string = <FILE>;
  close FILE;
}
{ local $/=undef; open FILE, "myfile" or die "Couldn't open file: $!"; $string = <FILE>; close FILE; }
open FILE, "myfile" or die "Couldn't open file: $!"; $string = join("", <FILE>); close FILE;
open FILE, "myfile" or die "Couldn't open file: $!";
while (<FILE>){
 $string .= $_;
}
close FILE;
open( FH, "sample.txt") || die("Error: $!\n"); read(FH, $data, 2000); close FH;

The format for the read function is:

read(filehandle, destination, size/length);

The example above will read 2000 bytes into the scalar variable $data.

my $file = 'sample.txt'; { local *FH; -f FH and sysread FH, my $file, -s FH; }
thanks to - perlmonks, roland, vroom, digitalkitty, katie, particle
Advertisements

Published by

Shafiq Alibhai

http://shafiq.in

One thought on “Perl – How to Read a Text File into a Variable – 6 ways to do it”

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s