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 filename.txt

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

Tagged , ,

Leave a Reply

Your email address will not be published. Required fields are marked *