A Perl write to file example

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.

Perl "write to file" example

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 "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\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);

Perl write to file - discussion

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.

Perl write to file - Summary

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.

 

Post new comment

The content of this field is kept private and will not be shown publicly.