This tutorial is a variation of the last one. As before, we read in lines of a data file and print them out with line numbers. The difference is that in this version, we specify the filename in the commandline parameters instead of redirecting standard input. (Feel free to compare the output of this script against that of the last one.) Once again, minimal error-checking is performed.

#!/usr/bin/perl
	
######################
#
# FILE: readfile02.pl
#
######################
#
# Read all the lines of a named input data file
# and print each line out with a line number.
#
	
use strict; # Declare strict checking on variable names, etc.
	
my $argc;   # Declare variable $argc. This represents
            # the number of commandline parameters entered.
my $lnum;   # Initialize line counter
my $fname;  # Declare file name variable
	
# Assign the number of commadline parameters to $argc
# Check the number
#
$argc = @ARGV;
	
if ($argc != 1)
{
  # If the number of commandline parameters is not 1,
  # print an usage message.
  #
  usage();  # Call subroutine usage()
  exit();   # When usage() has completed execution,
            # exit the program.
}
	
# You could use an else clause here, but it's not necessary
#
# Get the pathname and filename.
# Note: first item in a Perl array is at index 0, not 1
#
$fname = $ARGV[0];
	
# Open the file for reading, and assign arbitrary filehandle, FH.
# If the file does not exist or is otherwise unopenable, let the
# program stop gracefully with a message. (Note: some installations
# of Perl do not properly support the die() function).
#
open(FH, "<$fname") || die("Couldn't open file $fname\n");
	
#
# While there are lines to read from the data file, loop
#
	
while (<FH>)
{
  # The <FH> operator assigns the next line of data
  # from standard input to the Perl system variable $_.
  #
  $lnum++; # Increment the line counter
  chomp; # Remove the 'newline' character, '\n', from $_
  print "$lnum: $_\n"; # Print the line in brackets
}
exit(0); # Exit gracefully
	
sub usage
{
  # Display the usage of this script.
  # The first parameter is the filename,
  # including any absolute or relative path
  #
  print "Usage: perl readfile02.pl inputfilename\n";
}

This is #4 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: , , ,