Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: Replace a text in file at given offset with other text

by DrHyde (Prior)
on Feb 04, 2014 at 12:08 UTC ( #1073378=note: print w/replies, xml ) Need Help??

in reply to Replace a text in file at given offset with other text

'>>' 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;

Replies are listed 'Best First'.
Re^2: Replace a text in file at given offset with other text
by tarun28jain (Initiate) on Feb 05, 2014 at 04:11 UTC

    Thanks for the reply. This exactly solved my problem

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1073378]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2019-07-21 00:22 GMT
Find Nodes?
    Voting Booth?
    If you were the first to set foot on the Moon, what would be your epigram?

    Results (7 votes). Check out past polls.