how do i write to an existing file in perl?

You have to open a file in append (>>) mode in order to write to same file. (Use a modern way to read a file, using a lexical filehandle:)

Here is the code snippet (tested in Ubuntu 20.04.1 with Perl v5.30.0):

use strict;
use warnings;

my $filename = '/home/vkk/Scripts/outfile.txt';
open(my $fh, '>>', $filename) or die "Could not open file '$filename' $!";
print $fh "Write this line to file\n";
close $fh;
print "done\n";

For more info, refer these links – open or appending-to-files by Gabor.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top