Filehandles can be use to change the destination of the print
statement
just as they can change the source of input for the diamond operator. Simply
create a filehandle (or IO::File
object) opened for writing or appending,
and place the filehandle's name after the print
function, and before the
arguments to print
. Note that the filehandle is not an argument
to the print function, and must not be followed by a comma! Suppose we have
a series of files containing text, and we wish to create corresponding files with
the extension .html
containing the same text, but surrounded by some
minimal html directives. The following program would create a new file for each
file name provided on the command line:
foreach $file (@ARGV){ open(FILE,"<$file") || die "Couldn't open $file"; open(HTML,">$file.html") || die "Couldn't open $file.html"; print HTML "<html><body>\n"; while(<FILE>){ print HTML; } print HTML "</body></html>\n"; close(HTML); }The
printf
statement accepts filehandles in exactly the same way
as the print
statement.