Perl Replace String in File

This code snippet demonstrates how to replace string in file using perl. This perl script takes in an input file, replaces the all string foo with bar.

my $file = $ARGV[0];
my $filetmp = "$ARGV[0].tmp";
open (INPUT, "< $file") or die("Unable to open $file");
open (TMP, "> $filetmp") or die("Unable to open $filetmp");
while(<INPUT>) {
    if(/foo/) {
        s/foo/bar/;   # replace foo with bar   
    }
    print TMP $_;
}
close(INPUT);
close(TMP);
rename $filetmp, $file;