[perl] Search and replace a particular string in a file using Perl

Possible Duplicate:
How to replace a string in an existing file in Perl?

I need to create a subroutine that does a search and replace in file.

Here's the contents of myfiletemplate.txt:

CATEGORY1=youknow_<PREF>  
CATEGORY2=your/<PREF>/goes/here/

Here's my replacement string: ABCD

I need to replace all instances of <PREF> to ABCD

This question is related to perl

The answer is


A one liner:

perl -pi.back -e 's/<PREF>/ABCD/g;' inputfile

You could also do this:

#!/usr/bin/perl

use strict;
use warnings;

$^I = '.bak'; # create a backup copy 

while (<>) {
   s/<PREF>/ABCD/g; # do the replacement
   print; # print to the modified file
}

Invoke the script with by

./script.pl input_file

You will get a file named input_file, containing your changes, and a file named input_file.bak, which is simply a copy of the original file.