Reading all the lines of a data file is a very basic operation. Perl lets you do this in a number of ways. The method of feeding the data file to the Perl program can either be a redirect from the command line, or through a specified filename:

  1. > perl readfile.pl < inputfile.txt
  2. > perl readfile.pl inputfile.txt

This tutorial covers the first case. The next tutorial will cover the second case. Here is some sample code. Error-checking is left for later tutorials. This tutorial will be the basis of much of the future file manipulation examples.

#!/usr/bin/perl
	
######################
#
# FILE: readfile01.pl
#
######################
#
# Read all the lines of an input data file
# and print each line out with a line number.
#
	
use strict; # Declare strict checking on variable names, etc.
	
#
# While there are lines to read from standard input, loop
#
my $lnum; # Initialize line counter
	
while (<STDIN>)
{
  # The <STDIN> operator assigns the next line of data
  # from standard input to the Perl system variable $_.
  # You can also write <> instead of <STDIN>.
  #
  $lnum++; # Increment the line counter
  chomp; # Remove the 'newline' character, '\n', from $_
  print "$lnum: $_\n"; # Print the line number and line
}
exit(0); # Exit gracefully

This is #3 in a series of Perl scripts. Please feel free to leave comments if there is something that you would like to see. I cannot guarantee that I’ll be able to answer immediately, but I will answer as soon as I can.

Technorati Tags: , , ,