Hi,

you must be aware that a file is a stream of bytes. There is no inherent concept of a record or line. A line ends where a byte representing a Newline (UNIX-like) or two bytes representing ASCII-Carrige-Return and Newline are found.

So, when you have a substitution which makes the line longer, you need more bytes between the first and the one markin the end. That means you have to move the content or the whole rest of the file towards the end. If the substitution makes the line smaller you have to shift the whole rest of the file towards the beginning of the file.

Only when you know that the substitution will NOT change the length of a line you know that the line before the substitution and after the substitution will require the same space, you could implement something like you want.

In general you always produce a copy of the original file with all substitutions and delete the original afterwards.

When you're short of space you can split the original file into X parts having a certain count of lines, make the substitution with copy in that part and concatenate all resulting files afterwards. Something like that on a Unix shell:

split -l 1000 myfile myfile. for file in myfile.* do perl -i -pe 's/3/2/g' $file done cat myfile.* > newfile rm myfile myfile.*

where -l 1000 splits every 1000 lines and perl -i -pe 's/3/2/g' $file substitutes 3 by 2.

UPDATE: That is nonsense. With my example you copy the whole file in smaller pieces and gain nothing. I shouldn't talk to my children while answering questions here. Sorry.

Regards
McA


In reply to Re: Using read/write to update a file by McA
in thread Using read/write to update a file by PackerX

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.