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

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

  1. Pingback: Perl - comment lire un fichier texte dans une variable - 6 fa├žons de le faire

Leave a Reply