Tag Archives: open

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)

Continue reading


Reading a (text) file line by line with Perl

# Get the filename from the user via command line
$filename = $ARGV[0];
# Here we use the open command that reads a file (second parameter)
# and link it to a "handle" (first parameters, conventionally uppercase).
# "||" means "or", that is if open returns false... exit with an error message
open(FILE, "$filename") || die " FATAL ERROR:\n Unable to open \"$file\".\n";
# Now we retrieve line by line calling the file handle with < and >.
# Line content is stored in the special scalar "$_"
while (<FILE>) {
  print "$linecounter: $_";

to use this script we need to add a parameter to the command line: the filename! eg:

perl script.pl filename.txt

You can find a detailed tutorial on the open command here.

Tagged , ,