1.8.2 Treating Command Line Arguments as Files
Quite frequently, it is useful to write a program that takes a list of files as command line argument and performs the same action(s) on each of the files. Let us write a program that takes a list of files and prints out every line of every file to the userÕs terminal. If the program given below is stored as printfile.pl, the following call
%printfile.pl file1 file2 file3 file4
prints the contents of the four files on the terminal one file after the other.
Perl provides us with a simple mechanism to perform tasks repeated over two or more files that are given as command-line arguments. This is done by using the special input filehandle <ARGV>. When we write <ARGV> inside the conditional of a loop, it is taken by Perl to act as an input filehandle for each of the files mentioned in the command line. The files mentioned as command line arguments are considered for input sequentially.
Actually, something more happens if we use a variable like the special variable $_ (any other variable will work the same way) as the input variable along with the <ARGV> input filehandle. The first line of the first program is read into the $_ variable and printed. Next, the second line of the first file is printed and so on till the last line of the first file is printed to the terminal. At this time, the first line of the second file becomes available as the value of the $_ and is printed. The process is repeated and as a result every line of the second file is printed. Similarly, every line of every file mentioned as a command line argument is also printed. When the last line of the last file is read, the <ARGV> filehandle returns false and the reading and printing cycle finishes.
Program 1.13
#!/usr/bin/perl #file printfile.pl #This prints every line of every file give as args #A possible call is: printfile.pl file1 file2 file3 while ($_ =){ print $_; }
The <ARGV> filehandle is very useful in some circumstances. It is so useful that Perl provides us with a way to make it even shorter. If we leave out the filehandle and simply write < > in the conditional of a while or for loop, it is taken as <ARGV>. The program given above can also be written as the program given below.
Program 1.14
#!/usr/bin/perl
#file printfile1.pl
while (<>){
print;
}
Here, <> stands for an input handle that considers every file provided in the command line for input one after the other. In this program, we have also taken out the assignment to $_ inside the conditional of the loop since $_ is
taken as the default input variable if no assignment is done inside such a conditional. In addition, we have not given an argument to the print command which takes $_ as the default argument.
