I have a log file with some numeric data like

abc.log 12 15 17

I want to update the value present at offset 3 i.e 15 in this case with a given value like 20. I had done something like this

write_log("12345"); sub write_log { my ($message) = @_; my $new_data = ''; my $header_fields_value = 0; my $length = length $message; open (MYFILE, '>>', 'abc.log'); $header_fields_value = read_line(3); $new_data = $header_fields_value+$length+2; $header_fields_value =~ s/$header_fields_value/$new_data/g; seek(MYFILE,3,0); print MYFILE $header_fields_value; close (MYFILE); } sub read_line { my ($offset) = @_; open (MYFILE1, '<', $filename); seek(MYFILE1,$offset,0); my $line = <MYFILE1>; close (MYFILE1); return($line); }

here it is reading the value stored at offset 3 using read_line function. But modified value is being appended at the end of the file. I need it to replace the line present at offset 3.

Please help me in understanding what am i doing wrong or if it could be done in some easier way.


In reply to 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.