Perl Language Write to a file


This code opens a file for writing. Returns an error if the file couldn't be opened. Also closes the file at the end.

use strict;
use warnings;
use open qw( :encoding(UTF-8) :std ); # Make UTF-8 default encoding

# Open "output.txt" for writing (">") and from now on, refer to it as the variable $fh.
open(my $fh, ">", "output.txt")
# In case the action failed, print error message and quit.
or die "Can't open > output.txt: $!";

Now we have an open file ready for writing which we access through $fh (this variable is called a filehandle). Next we can direct output to that file using the print operator:

# Print "Hello" to $fh ("output.txt").
print $fh "Hello";
# Don't forget to close the file once we're done!
close $fh or warn "Close failed: $!";

The open operator has a scalar variable ($fh in this case) as its first parameter. Since it is defined in the open operator it is treated as a filehandle. Second parameter ">" (greater than) defines that the file is opened for writing. The last parameter is the path of the file to write the data to.

To write the data into the file, the print operator is used along with the filehandle. Notice that in the print operator there is no comma between the filehandle and the statement itself, just whitespace.