Your original code as BrowserUK said is writing the replacement after moving past the 2. And moritz is right that reading from the file and writing to a temp is better most of the time. If you have forgo the the temp file, something like the following could work:

open FH, '+<afile'; $temp = ''; while (<FH>) { s/2/two\nhi hello/; $temp .= $_; } seek(FH, 0, 0); print FH $temp; truncate(FH, tell(FH)); close(FH);

this deals with the '2' when it finds it instead of after passing it. As long as your file isn't huge, like a logfile, this isn't too much of a memory hog. If I'm going to do it in memory, I do something more like the following than all that "IOish" stuff above.

sub slurp { my $file = shift; open my $fh, '<', $file or return undef; local $/ unless wantarray; return <$fh> if defined wantarray; } sub jot { my $notepad = shift; open my $fh, ">", $notepad or die $!; print $fh @_; } my $temp = slurp 'file.txt'; $temp =~ s/2/two\nhi hello/; jot 'file.txt', $temp;

The lexically scoped filehandle, $fh, goes out of scope when slurp returns and $fh is automatically closed before jot begins. slurp will return an array of lines if called with an array, or a string containing the whole file if called with a scalar as I did.


In reply to Re: what is the best method to read and write in a file in perl by jakeease
in thread what is the best method to read and write in a file in perl by Anonymous Monk

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.