How to read and append to a file using perl

A file in perl can be opened by using the below code snippet:

open(FH, 'test.txt');

The above code snippet opens the file in read mode. To open the file in read and append mode, following code snippet can be used:

# Open the file in read and write mode
open(FH, "+"
);
# Write the logic to read the file here

# Move file position to end of file
seek(FH, 0, 2);

#append here
print FH "Appending to file";
close(FILE);

Now, the question occurs why below code snippet doesn’t work:

open(FH, "+>>test.txt");

Issue with the above code snippet is that it allows to append to the file, but does not allow to read the contents. This is because the file is opened for append, which automatically moves the file position to the end. So there is nothing to be read.

Hope you find the information presented here useful. Please leave your queries or feedback in the comments section below.

  1. this code is not working. I got your concept of
    open(FH, “+>>test.txt”);

    but i tried the above code and it’s not working.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">