Perl Script : Cat

cat
The UNIX cat utility takes a list of file names as command-line arguments, and prints the contents of the files. Here is a Perl program that does pretty much the same thing.
use strict;
use warnings;
sub print_file {
my $file = shift;
open FILE, $file;
while (my $line = <FILE>) {
print $line;
}
}
sub cat {
while (my $file = shift) {
print_file $file;
}
}
cat @ARGV;
There are two subroutines here, print file and cat. The last line of the program invokes cat, passing the command-line arguments as parameters.
cat uses the shift operator inside a while statement in order to iterate through the list of file names. When the list is empty, shift returns undef and the loop
terminates.

Each time through the loop, cat invokes print file, which opens the file and then uses a while loop to print the contents.


No comments:

Post a Comment