例如把dir1和dir2两个目录下的所有.c和.h文件下的abc()函数替换成def()函数。下面的脚本会把改动前的文件存为以.old为后缀的文件。
?
#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
sub process_source_file {
?my $in_filename = $_[0];
?my $full_path = $_[1];
?my $out_filename = "cleanup_filename"; # a temp name
?print "source file ",$full_path,"n";
?open(my $in,"<",$in_filename) or die "Can't not open file $full_path: $!n";
?
?$/ = undef; ?# treat the whole file as a single string
?my $body = <$in>;
#?print $body;
?if (! ($body =~ /babcs*(/)) {? # unnecessary to proceed
??print "No specified pattern foundn";
??close $in or die "$in: $!n";
??return;
?}
?open(my $out,">",$out_filename) or die "Can't not open tmp file: $!n";
?$body =~ s/babcs*(/def(/g;
?print $out $body;
?close $in or die "$in: $!n";
?close $out or die "$out: $!n";
?rename($in_filename,"$in_filename.old");
?rename($out_filename,$in_filename);
}
sub process_file {
?# $File::Find::dir is the current directory name
?# $_ is the current filename within that directory
?# $File::Find::name is the complete pathname to the file
#?print "processing ",$File::Find::name,"n";
?if (-d $_) {
#??print $File::Find::name," is a directoryn";?
?} else {
??if ($_ =~ /.[ch]$/i) {
???#print "$_ = ",$_,",File::Find::name = ","n";?
???process_source_file($_,$File::Find::name);
??}
??#print $File::Find::name," is a filen";
?}
}
my @DIRLIST = ("dir1","dir2"); find(&;process_file,@DIRLIST);