$filepath = "C:\\Perl scripts\\test"; # $GetName is a filename that they want to use as a template # to change all the filename that are similar within a # directory(user input, they will add the parentheses also). # The parentheses () are used for a parameter # they want to keep for adding to the final file name $GetName = "test_0(02.txt)"; # $StartCh is the 1st number they want to start with, so # for this example $StartCh = 1; $EndtCh = 12; # $SetName is the final filename so for example # the 1st file lets say is test_001.txt. # Based on the $GetName and the SetName the final filename # should be changed to "Chapter 01.txt". $SetName = "Chapter \1"; opendir (DIR, $filepath) || die("Cannot open directory"); while ($file = readdir DIR) { print "$file\n"; # Matches for anything before parentheses if ($GetName =~ m/(.*?)\(/) { $subname = $1; if ($file =~ /^$subname/) { for ($i = $StartCh; $i <= $EndtCh ; $i++) { # This reg ex could possible match alot more than I want. # It would give me the wrong result, for example # if the filename is "test_005_1.txt", it would pick # it up even though thats not what I want if ($file =~ /$i/) { # This is where I am going to have problems # especially if they do something like this # $GetName = "test_(02-092010.doc)" the # number of digits would be totally off my(@origdig) = ($GetName =~ m/\d/g); my $orig_cnt = scalar(@origdig); if ($StartCh => 1 and $EndtCh =< 9 and $orig_cnt=1) { $num1 = $origdig[0]; $replace = $subname . $i; } if ($StartCh => 1 and $EndtCh =< 9 and $orig_cnt=2) { $num1 = "0" . $origdig[0]; $replace = $subname . $i; } # In case they may include the extra 0 # example $GetName = "test_(002.txt)". if ($StartCh => 1 and $EndtCh =< 9 and $orig_cnt=3) { $num1 = "00" . $origdig[0]; $replace = $subname . $i; } # More If stmts to do the same for >= 10 # How would I go about writing this to be more # efficient and be cleaner? } } } else { print "$file does not match\n"; } } else { print "GetName didnt have parentheses\n"; } } closedir DIR; Example of file names in the directory in this case: test_001.txt test_002.txt ... ... test_012.txt