Perl script to rename files in a directory tree I'm taking a scripting language course with no prior scripting language or Linux experience, though I've taken classes in VB, Java, and C++. Our first assignment is to write a script that will traverse the directory tree of the location the script is run from and rename the files according to some predetermined rules. In this case, directories are to have spaces, \", and any .hxx or .cxx extensions removed. Files get the same treatment except their extensions are changed to .h or .cpp respectively. Also, the script isn't supposed to actually change the file names, just produce a file with the commands to do so, mine are bash commands in the form of mv 'old file name' 'old_file_name'.

#!/usr/bin/perl -w

use Cwd;
use File::Find;
use strict;

my $file = "output.txt"; 
my $dir = getcwd;

# Creates file to print output to, Die with error message if we can't open it
open my $fh, '&gt;&gt;', $file 
    or die "$file: $!\n";

# traverse the directory tree
find(\&amp;process_files, $dir);

# creates a file of bash rename scripts
sub process_files
{
    my $s1 = $_;    
    if (-f) 
    {
        $s1 =~ s/\s/_/g;
        $s1 =~ s/\"//g;
        $s1 =~ s/\.cxx/\.cpp/g;
        $s1 =~ s/\.hxx/\.h/g;
        print $fh "mv '" , $_ , "' " ,  $s1 , "\n";
        print "mv '" , $_ , "' " ,  $s1 , "\n";
    }
    if (-d) 
    {
        $s1 =~ s/\s/_/g;
        $s1 =~ s/\"//g;
        $s1 =~ s/\.(cxx|hxx)//g;
        print $fh "mv '" , $_ , "' " ,  $s1 , "\n";
        print "mv '" , $_ , "' " ,  $s1 , "\n";
    }
}
close $fh;
It seems correct to me except these lines:

$s1 =~ s/\.cxx/\.cpp/g;
$s1 =~ s/\.hxx/\.h/g;
$s1 =~ s/\.(cxx|hxx)//g;


There're no needs to do the substitution g lobal and also you need to anchor the regex at the end:

$s1 =~ s/\.cxx$/.cpp/;
$s1 =~ s/\.hxx$/.h/;
$s1 =~ s/\.(cxx|hxx)$//;