Reading a text file from Perl

This short tutorial is to remember how to read a file from Perl. You should remember that it’s a two steps strategy:

  1. Open the file (that means connect to it)
  2. Read the file line-by-line (with a while loop)

The open command

the open command requires two arguments:

  • a filehandle, that is a “label” for the file content, a nickname.
  • the file name, that is the full path to the file.

The function iself returns TRUE if successful, FALSE if Perl can’t read the file.

An example:

open(F, "/home/geno-30/file.txt");

Reading a file line by line

Here we post a complete program, called cat.pl, that prints the content of a file. The source is available here.

#!/usr/bin/env perl
 
print STDERR " This program prints the content of a text file\n";
print STDERR " PARAMETER: FileName\n";
 
($filename) = @ARGV;
 
if ($filename eq '') {
   die " FATAL ERROR:\n Missing parameter (file name).\n";
}
 
if (open(TEXT, "$filename") == 0) {
   die " FATAL ERROR:\n Unable to read the file \"$filename\".\n";
}
 
while ($line = <TEXT> ) {
   $linesCounter++;
   chomp($line);
   print "$line\n";
}
 
print STDERR " End. $linesCounter lines printed.\n";
Tagged

One thought on “Reading a text file from Perl

  1. […] fellows, here you are the slides we used yesterday. Don’t forget to study this example, […]

Leave a Reply

Your email address will not be published.