Tag Archives: file

Reading a file from Perl

This post explains how to read a file from Perl. This is an optional part of laboratory04, so don’t try this unless you really feel confident about all the rest.

Continue reading

Tagged , ,

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 , ,