Think of the file data on the disk as a sequential stream of bits (this is an approximation- but a good thought model here). Or perhaps a sequence of numbers: 123789, if we want the sequence 1234789, that means that the data 789 has to move down to make room! We have to carve a "hole" for the new "4" data and that is a complex thing to do. If say, the new "4" data is exactly the same size as the "7" data, and I mean *EXACTLY*, we could use seek() to move to that position and wind up with 123489 (replace 7 data with 4).
Think of cassette tapes, if you record 3 songs and you want to add a new song at the beginning of the tape, you have to record the new song and then all of the next 3 songs over again. The disk works like that.
Far and away your best bet if these files aren't huge, is to
open the file for read, slurp it into a memory array, do what want to that data, open a new file for write, write the data, close the file and then delete the old file and rename the new file to the old file's name.
Tie::File would do some grunt work for you, but this is what it essentially does and its not portable to Windows if that matters to you.
To be frank, you are in way over your head if you intend to write something that can insert things into an existing file by yourself. That is definitely not beginner stuff!
If the idea of reading the file into memory, working on it and writing it back out doesn't work, then this is time for using a Perl DB module or Tie::File.
Anyway it works this way because the hardware works that way.
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.