in reply to How can I replace a single character (digit) in a file

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.

Replies are listed 'Best First'.
Re: Re: How can I replace a single character (digit) in a file
by sofreshsoclean (Initiate) on Jul 30, 2001 at 05:52 UTC
    Thanks for your guidance, the seek command worked like a charm. Here's what I ended up using:
    open THIS_FILE, "+<$listOption" or die "ERROR: SearchFile: $!"; while (<THIS_FILE>) { if (/^$genre\t\d$/) { seek(THIS_FILE, -2, 1) or die; print THIS_FILE $option; seek(THIS_FILE, 1, 1) or die; } } close THIS_FILE;
    Pretty close to what you updated to. It took me a while to realize I shouldn't be using the 8 char read.

    Thanx
    -Zach (SFSC)

Re: Re: How can I replace a single character (digit) in a file
by ides (Deacon) on Jul 30, 2001 at 01:20 UTC
    This is a much better solution than mine. :)

    -----------------------------------
    Frank Wiles <frank@wiles.org>
    http://frank.wiles.org