Appending to files
In this episode of the Perl tutorial we are going to see how to append to files using Perl.
In the previous episode we learned how to write to files. That's good when we are creating a file from scratch, but there are cases when you would rather keep the original file, and only add lines to the end.
The most prominent case is when you are writing a log file.
This article shows how to do this using core perl function. There is a more modern and more readable way using Path::Tiny.
open(my $fh, '>', 'report.txt') or die ...
Opening a file for writing using the > sign will delete the content of the file if it had any.
If we would like to append to the end of the file we use two greater-than signs >> as in this example:
open(my $fh, '>>', 'report.txt') or die ...
Calling this function will open the file for appending. that means the file will remain intact and anything your print() or say() to it will be added to the end.
The full example is this:
use strict; use warnings; use 5.010; my $filename = 'report.txt'; open(my $fh, '>>', $filename) or die "Could not open file '$filename' $!"; say $fh "My first report generated by perl"; close $fh; say 'done';
If you run this script several times, you will see that the file is growing. Every run of the script will add another row to the file.
Prepending to the beginning of a file
In case you'd like to the top of the file there is another article explaning how to write to the beginning of a file.
Published on 2013-03-15