Perl write to file FAQ: Can you demonstrate an example of how to write to a file in Perl?
Somehow I managed to go all these years without showing a simple Perl "write to file" example. Let's fix that.
Here's a short snippet of code that shows how to write to a file in Perl:
# somewhere earlier in the code I define my filename ... my $outfile = 'footer.html'; # here i 'open' the file, saying i want to write to it with the '>>' symbol open (FILE, ">> $outfile") || die "problem opening $outfile\n"; # here i print a plain text line to the file print FILE "<div align=\"center\">\n\n"; # write an array of lines to the file here print FILE @lines1; # print another plain text line to the file print FILE " \n\n"; # write a second array of lines to the file print FILE @lines2; # print a closing div tag to the file print FILE "</div>\n"; # i close the file when there's nothing else i want to write to it close(FILE);
As you can see in this Perl write to file example, this code writes its output to a file named "footer.html". Note that the Perl print statements shown here are very similar to normal Perl print statements, except I precede the text that is printed with the Perl filehandle name (named "FILE" in this example).
I also print two arrays to this output file in this example. FWIW, I create those arrays by reading from two input files, like this:
open (F1, $randomFile1); my @lines1 = <F1>; close (F1);
As you might guess by looking at the code, $randomFile1 is the name of an input file that I've chosen at random from a directory that contains a collection of files.
While this Perl write to file example may not seem like much, I use code like this display random ads in the footer section of "Java Warehouse" pages like this one.