Perl (Scripting) - Open file for writing appending overwriting (> and >>)

by
Jeremy Canfield |
Updated: February 03 2024
| Perl (Scripting) articles
open is used to try to open a file for reading or writing.
- open < is used to open a file for reading
- open > is used to open a file for writing, and the file will be overwritten
- open >> is used to open a file for writing, to append new lines to the file
In this example, the file is overwritten to contain "Line 1 Line 2 Line 3".
my $file = "/path/to/file.txt";
my $dirname = File::Basename::dirname($file);
if (not -e $dirname) { `mkdir --parents $dirname`; )
if (open FH, ">", $file and -w $file) {
print FH "Line 1\n";
print FH "Line 2\n";
print FH "Line 3\n";
close FH;
}
else {
print "failed to open $file due to the following: $! \n";
exit 1;
}
In this example, "Hello World" is appended to the end of the file.
my $file = "/path/to/file.txt";
my $dirname = File::Basename::dirname($file);
if (not -e $dirname) { `mkdir --parents $dirname`; )
if (open FH, ">>", $file and -w $file) {
print FH "Hello World\n";
close FH;
}
else {
print "failed to open $file due to the following: $! \n";
exit 1;
}
Did you find this article helpful?
If so, consider buying me a coffee over at