Sure you can, BUT the new record (line) must be exactly the same length as the old one. For example, if you just want to comment out a line by placing a '#' at the front then you cannot overwrite the existing line since that would be one extra character - you would overwrite the first character of the next line in the file.

Here is a simple example where the new line is the same length as the old:
use warnings; use strict; use Fcntl qw(SEEK_CUR); # open existing file for read/write open (my $in, '+<', 'file1.txt') || die "Unable to open file1.txt:$!"; while (<$in>) { # Identify the record if (/4444/) { # Construct the new record s/4/#/g; # Position the file pointer seek ($in, -length($_)-1, SEEK_CUR); print $in $_; } } close $in;
Input file was:
111111111111111 22222222 33333333333 4444444 5555555555555555 66666666666
file after processing is:
111111111111111 22222222 33333333333 ####### 555555555555555 66666666666

In reply to Re^5: substitute on file line by line not working syntax error by cdarke
in thread Search and Replace line by line not working on Filehandle by matze77

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.