You should be able to achieve the writing part of this by opening the file for read and write, then using a combination of tell and seek to a) know where you have read to, b) set where to write to, and c) (if needed) restore the position for further reading.

It might look something like the following (untested); I've left placeholder functions for the bits you need to supply.

# you'll need to provide $filename open(my $fh, '+<', $filename) or die "Error opening $filename: $!"; # create a scope to localize the input record separator { # use formfeed as input record separator local $/ = "\x{0c}"; # track position of start/end of current record my($start_pos, $end_pos) = (undef, 0); while (defined(my $record = <$fh>)) { ($start_pos, $end_pos) = ($end_pos, tell($fh)); # placeholder: decide if this record needs to be changed next unless needs_change($record); # placeholder: work out what change should be made my($offset_to_write_at, $text_to_write) = required_change($record) +; seek($fh, $start_pos + $offset_to_write_at, 0) or die "Error seeking to $start_pos + $offset_to_write_at"; print $fh, $text_to_write or die "Error writing update"; # ready to read next record seek($fh, $end_pos, 0) or die "Error seeking to $end_pos"; } } close $fh or die "Error closing filehandle, writes may not have comple +ted";

Note that seek and tell deal with byte offsets, so if your data is not ASCII you need to take extra care when determining the correct offset to write at.


In reply to Re: Changing string in specific line/position in a file by hv
in thread Changing string in specific line/position in a file by onemojofilter

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.