You can do it using one of the easy ways, or one of the hard ways. The hard way is to open the file for read/write, read the target line, formulate a replacement line of exactly the same number of bytes, seek back to the start of the line, and write it back out. Be sure to obtain a file lock while you're there.

An easier way would be to open a temporary output file (see File::Temp), read the input file, simultaneously writing to your temp file. When you get to the line(s) you need to change, make your change and write them out to the output file too. Continue through to the end of the file. Close both files. Rename the output file over the input file. It would be wise to test your output thoroughly, at least while in development to make sure your plan worked before you go clobbering your input file. If there's any possibility your input file could get modified while you're working be sure to obtain a lock.

Another easy solution is to use Tie::File. Find the line(s) of interest, make your change, and make your changes. Tie::File handles some of the details without you dealing with them. But locking could still be important in a multi-user environment.

I would prefer the second solution if it were me. An alternate on that strategy would be to rename the input file to input.name.bak, iterate over it, writing to a new file with the original file's name. Now you've got a backup.


Dave


In reply to Re: Rewriting into file by davido
in thread Rewriting into file by pr09

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.