Editing files inplace is tricky. One has to remember than on most
platforms, including UNIX and Windows, files are just sequences of
bytes. There is no line based datastructure. Your approach isn't
going to work,
unless the replacement part is the same
length (in bytes) as what you are replacing. But then you are still
missing a seek (you need to seek back to reposition the file pointer)
and a print.
There are two often used approaches for generic modifications:
- Read in the entire file into memory. Make the modifications,
seek back to the beginning of the file, and print the modified
content. Don't forget to perform a truncate, otherwise you
may end up with trailing garbage if the modified text is
smaller than the original. Obviously, this approach works
better for small files than huge files.
- Use a temp file. Read in parts (for instance lines) of the
original file, do the modifications, and write the modified
text to the temp file. If you are all done, move the temp
file to the original file.
You may want to use Tie::File, or investigate the
-i option of perl itself (or its $^I
equivalent).
Abigail
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.