## Open our file for reading and writing: open(MYFILE, "+< $myfile") or die "Could not open $myfile: $!\n"; ## File locking would be a Good Idea here ## Loop through the file one line at a time while() { if (/$foo/) { ## We have a match! my $tellme = tell(MYFILE)-length $_; ## See below my @baz = ; ## Slurp everything from that point forward unshift(@baz,$_); ## Throw our string back in ## Above, we stored the location in the file where the ## first line was that matched. Now we rewind to that point. seek(MYFILE,0,$tellme); ## The file from where we are (via seek) to the end of ## the file is now in memory, inside @baz for (@baz) { s/$foo/$bar/; print MYFILE $_; } ## Now we must cleanup our file, especially if the ## file has shrunk from our changes: truncate (MYFILE,tell(MYFILE)); last; ## Bail from the original MYFILE loop } }