in reply to Changing string in specific line/position in a file
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Changing string in specific line/position in a file
by GrandFather (Saint) on Oct 31, 2022 at 20:23 UTC | |
by hv (Prior) on Oct 31, 2022 at 20:32 UTC |