'>>' opens the file in *append* mode, which is why your data gets appended. You need to open the file in read/write mode, seek() to the appropriate offset, and then write the replacement. Beware that the replacement must be exactly the same length as the original. Given a file with contents thus:

15 20 25
This code will replace the 20 with 94:
use Fcntl qw(:seek); open(my $fh, '+<', 'foo'); seek($fh, 3, SEEK_SET); print $fh '94'; close($fh);

If you can't guarantee that the original and replacement text are the same length, then read the file, use an l-value substr() on the data, and write it back out again. The example below replaces the two characters at position three in the string with *three* characters. Obviously you'll need to handle opening, reading and writing the file yourself, but that's trivial:

$foo = "ab cd ef"; substr($foo, 3, 2) = "cat"; say $foo;

In reply to Re: Replace a text in file at given offset with other text by DrHyde
in thread Replace a text in file at given offset with other text by tarun28jain

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.