Page 1  2
Let's explain what's happening word by word.

Perl invokes the Perl interpreter. Normally, you'd run a Perl program by typing "perl progname.pl", but Perl also allows you to send it a Perl command for execution. The trick is in the three little command line switches p, i, and e.

The Perl manual (type "man perlrun") says that the -p command line switch causes Perl to assume the following loop around your program, which makes it iterate over file name arguments somewhat like sed:

LINE:
while (<>) {
... # your program goes here
} continue {
print or die "-p destination: $!\n";
}


In plain English, Perl will apply our script to each line in a specified file or files (in this case all files ending with .html). In our example, the Perl substitution command "s/images/pix/," which substitutes the text "pix" for the text "images," is run against every line in the file.

The I switch "specifies that files processed by the <> construct are to be edited in place. It does this by renaming the input file, opening the output file by the original name, and selecting that output file as the default for print() statements. The extension, if supplied, is used to modify the name of the old file to make a backup copy, following these rules: If no extension is supplied, no backup is made and the current file is overwritten. If the extension doesn't contain a *, then it is appended to the end of the current filename as a suffix. If the extension does contain one or more * characters, then each * is replaced with the current filename."

Our example renames the original file by adding the extension ".orig" to the end of the filename. That's a good idea in case the substitution produces unexpected results.

The -e switch executes the following quoted text as a Perl command. In this case, s/images/pix/ substitutes pix for images wherever it occurs in each file.

In one line we've effectively run the following Perl program against all the files specified (.html). It's powerful constructions such as these that make Perl a favorite among hackers and webmasters everywhere.

#!/usr/bin/perl
$extension = '.orig';
LINE: while (<>) {
if ($ARGV ne $oldargv) {
if ($extension ! ~ /\*/) {
$backup = $ARGV . $extension;
}
else {
($backup = $extension) =~ s/\*/$ARGV/g;
}
rename($ARGV, $backup);
open(ARGVOUT, ">$ARGV");
select(ARGVOUT);
$oldargv = $ARGV;
}
s/images/pix/;
}
continue {
print; # this prints to original filename
&}
select(STDOUT);


Perl resources

Page 1  2