$_
successively to each file in the current
directory whose filename matches that text argument. This provides an easy
way to process all files with common names from within a perl program, without
having to rely on the shell to expand wildcards through the command line.
To illustrate, let's say we want to find the longest line of all of the html programs
stored in a directory. Since these programs have the suffix ``.html
'',
the expression ``*.html
'' will match all of the files we want. The program
will have an outer loop, driven by the diamond operator with a text argument, and an
inner loop, also driven by the diamond operator, but with a filehandle, to
process each file:
while(<*.html>){ open(FI,"<$_") || die "Couldn't open $_"; $file = $_; $maxlen = 0; while(<FI>){ $maxlen = length if length > $maxlen; } close(FI); print "$file: $maxlen\n"; }It was necessary to store the name of each file in the variable
$file
, because the value stored in the $_
variable
of the outer loop (which represents the name of the file being processed) gets
overwritten by the inner loop (where $_
represents the current input line.).