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:

  1. 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.

  2. If you are writing to the file only if it is empty, then appending (>>) is the same as simply writing (>).

  3. 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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.