Hi,

I was trying to understand the write read mode of file handling in perl (+>). For the same I've written the below program.

1 #!/usr/bin/perl 2 use strict; 3 use warnings; 4 5 open my $FH , "+>", "input"; 6 7 my @contents = <$FH>; 8 print "@contents\n"; 9 10 print $FH "4\n"; 11 12 @contents = <$FH>; 13 print "@contents\n"; 14 close($FH); Before executing the perl script: Initial file ananda@ananda-desktop:~/Documents/perl_programs/try$ cat input 1 2 3 ananda@ananda-desktop:~/Documents/perl_programs/try$ perl test.pl ananda@ananda-desktop:~/Documents/perl_programs/try$ cat input 4 ananda@ananda-desktop:~/Documents/perl_programs/try$ After executing the perl script: Updated file

What I was expecting is print statement at line 13 in the code will produce an output of 4. But it did not happen that way. The list was empty and hence the output was blank.

My guess is the write operation into the file has written the data into primary memory and not yet into the secondary storage (Hard disk). The data will be written into secondary storage only when we close the file handle.

If the above assumption is right, then is there any way to store the modified data back to the secondary storage by any other means other than closing the filehandle.

If the above assumption is wrong, can someone explain the reason for the above behaviour

Thanks,

Ananda


In reply to Clarification on the write read mode of filehandling by I_love_perl

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.