Befall Befall - 5 months ago 7
Perl Question

SIMPLE file reading in Perl

How does Perl read in files, how does it tell it to advance to the next line in the text file, and how does it make it read all lines in the .txt file until, for example, it reaches item "banana"?


Basically, there are two ways of reading files:

  1. Slurping a file means reading the file all at once. This uses a lot of memory and takes a while, but afterwards the whole file contents are in memory and you can do what you want with it.
  2. Reading a file line-per-line (in a while loop) is better if you don't want to read the entire file (for example, stop when you reach "banana").

For both ways you need to create a FILEHANDLE using the "open" command, like so:

open(my $yourhandle, '<', 'path/to/file.txt') # always use a variable here containing filename
    or die "Unable to open file, $!";

Then you can either slurp the file by putting it into an array:

my @entire_file=<$yourhandle>; # Slurp!

or read the file one by one using a while loop

while (<$yourhandle>) { # Read the file line per line (or otherwise, it's configurable).
   print "The line is now in the $_ variable";
   last if $_ eq 'banana'; # Leave the while-loop.

Afterwards, don't forget to close the file.

    or warn "Unable to close the file handle: $!";

That's just the basics.. there's a lot to do with files, especially in Exception handling (what to do when the file does not exist, is not readable, is being written to), so you'll have to read up or ask away :)