#! /usr/bin/perl
## repsif.pl Version 0.0.1
## REPlace String In File
## Copyright (C) 2000 Yoshio Shimamura

## global data
$temp_ext = '.tmp';

## change directory as you like.
print "Enter Directory Name: ";
chop($dir = <STDIN>);
chdir($dir) || die "Cannot chdir to $dir";

## accept strings
print "Enter Old String: ";
chop($sstr = <STDIN>);
print "Enter New String: ";
chop($rstr = <STDIN>);

## store file name to array
opendir(DIR, '.') || die "Cannot open $dir";
@files = readdir(DIR);
closedir(DIR);

## call subroutine per file
for (@files) {
    next if -d $_; # ignore directory
    &rep_str_in_file($_, $sstr, $rstr);
}

## replace string in file
sub rep_str_in_file {
    local($infile, $old, $new) = @_;

    open(INFILE, $infile) || die "cannot open $infile";

    $outfile = $infile.$temp_ext;

    if (-e $outfile) {
	die "$outfile already exists";
    }

    open(OUTFILE, ">$outfile") || die "cannot write $outfile";

    while (<INFILE>) {
	s/$old/$new/g;
	print OUTFILE $_;
    }

    close(INFILE);
    close(OUTFILE);

    unlink($infile);
    rename($outfile, $infile);
}
