3.1.20 Reading a File in One Swoop

We know by now that a file handle can be used to read a line at a time form a file. For example, if we write

open IN, "input.txt";
$line = ;

$line has the first line of the file input.txt. We can easily write a while loop that reads every line of the file and performs some task. Here $line is a scalar. Therefore, the reading of the file takes place in scalar context. In scalar context, the angle bracket operator (i.e., <>) operator reads the next line from the file specified in the filehandle. However, there may be situations where we may want to read the whole file in one read operation. This happens if <> is used in array or list context. For example, if we write

@lines = <IN>;

all the lines in the file specified by the handle IN will be read. Each line read will be an element of the array @lines. The lines are available in the same sequence as they occur in the file. We are assuming that we have a text or ASCII file. The following program simply prints the number of lines in a text file.

Program 3.29

#!/usr/bin/perl
use strict 'vars';
open (IN, "input.txt");

my @lines = ;
my $lineCount = $#lines + 1;
print "Number of lines in the file = $lineCount\n";

The output of this program is something like the following.

Number of lines in the file = 131