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

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

15 March 2010

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;
  }