Here's one way to do it, supposing you wanted to change the number after "pref3" from 0 to 9:
open(PREF,"+< preffile") or die; while (<PREF>) { # if we see pref3 set to 0 if (/^pref3\t0$/) { # you need to rewind two chars to get # before the 0 and the newline , which # you've already gone past seek(PREF,-2,1) or die; # print a "9" in this spot print PREF "9"; # move forward one char past the newline # to continue reading. seek(PREF,1,1) or die; } } close PREF;
See open for the <+ read-write mode, and seek for the seek() bit.

Update: I should note that this only works when the replacement string is the same length as the original. See "perldoc -q 'how do I change one line'" for a complete answer.

Update2:Replaced the read() with while(<PREF>), since it's not likely that all the lines in the file are 8 chars long.


In reply to Re: How can I replace a single character (digit) in a file by kschwab
in thread How can I replace a single character (digit) in a file by sofreshsoclean

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.