Sethsdad's method works very well, and it's such a common desire that there's a built-in way that simplifies things a bit.
If you set the
$^I default variable and use the
<> operator, you can edit the file in place and get a backup for free. Behind the scenes, Perl takes care of duping the file safely and making the backup for you:
Code:
# Set the suffix for backups to '.bak' and turn on in-place editing
$^I = '.bak'
while (<>) {
s/bob/larry/g;
}
That's it. The only trick is that when you run this, Perl will perform the substitution on whatever files you specify on the command line. So if the file you want to edit is data.txt, save this script as editor and then you call it as
perl editor data.txt.