1.6.1 Reading from a file

The program given below prompts for the name of a file. When the user types in the name of a file, the program prints out the contents of the file with the lines numbered one by one.

Program 1.9

#!/usr/bin/perl
#file name: read-file.pl
use strict;
my ($filename, $linecount);

print "Please give me a file name >> ";
$filename = ;
chomp ($filename);

$linecount = 1;
print "Printing file $filename\n\n";

open (INFILE, $filename);
while (){
    print "$linecount\t$_";
    $linecount++;
    }

To read from a file, Perl opens a filehandle. Here the filehandle is called INFILE. Opening the filehandle INFILE associates the filehandle with the file whose name is the value of the $filename variable. In this case, the value of the variable $filename is obtained by reading the userÕs input at the terminal. This value is a string.

The conditional of the while loop ensures that every line of the file is read and printed on the terminal. Each line is preceded by the line number. The line number is incremented every time a line is read and printed. ++ is the increment operation; it has two plus signs with no intervening space. The operator is used here in the postfix format. In other words, the operator follows the argument. Incrementing is done by 1.

An interaction with this program is given below. Here, we read the file containing the above program itself.

% perl file-read.pl
Please give me a file name >> file-read.pl
Printing file file-read.pl

1       #!/usr/bin/perl
2       #file name: read-file.pl
3       use strict;
4       my ($filename, $linecount);
5
6       print "Please give me a file name >> ";
7       $filename = ;
8       chomp ($filename);
9
10      $linecount = 1;
11      print "Printing file $filename\n\n";
12
13      open (INFILE, $filename);
14      while (){
15          print "$linecount\t$_";
16          $linecount++;
17          }