Hello leelu, and welcome to the Monastery!
Immediately after an appending operation, the file pointer is positioned at the end of the file, so a read operation will always return nothing. You first have to seek to the position where you want to begin reading. The following script is my take on what (I think) you are trying to do:
#! perl use strict; use warnings; use Fcntl ':seek'; my $file = 'aaa.txt'; if (!-e $file || -z $file) { # print "File '$file' is empty\n"; open(my $fh1, '>', $file) or die "Cannot open file '$file' for writing: $!"; print $fh1 "The quick brown fox jumped over the unfortunate dog.\n +"; close $fh1 or die "Cannot close file '$file': $!"; } open(my $fh2, '+>>', $file) or die "Cannot open file '$file' for appending and reading: $!"; print $fh2 "We have nothing to fear but fear itself.\n"; seek $fh2, 0, SEEK_SET; print while <$fh2>; close $fh2 or die "Cannot close file '$file': $!";
Notes:
Like all file test functions, -z returns undef (a false value) if the file does not exist. So you need to test for existence as well as zero size.
If you are writing to the file only if it is empty, then appending (>>) is the same as simply writing (>).
SEEK_SET is defined in the Fcntl module. It specifies the start of the file as the position at which the offset (in this case, 0) is applied.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re: Applying multiple file modes
by Athanasius
in thread Applying multiple file modes
by leelu
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |