You can reduce the amount of work by restricting the file list to those which actually contain "Closed". Do that by replacing opendir . . . readdir . . . closedir with glob. You can also shorten your loop code a little by taking advantage of $_ and its properties.
#!/usr/bin/perl use strict; use warnings; my $dir = 'C:\Tickets'; chdir $dir or die "Error - Please check that $dir exists and is accessible.\n +"; my @fileList = glob '*Closed*'; foreach (@fileList) { next if -d; my $oldname = $_; s/Closed/Open/; rename $oldname, $_; }
I also removed the big if..else by just dieing with the error message if chdir fails. That would avoid closedir on a bad handle in your code. Moving closedir inside the affirmative branch would do that, too.
Update: You can remove the dependence on chdir entirely by including $dir in the glob pattern. With the error handling for rename added, the new version looks like this,
#!/usr/bin/perl use strict; use warnings; my $dir = 'C:\Tickets\'; my @fileList = glob "${dir}*Closed*"; foreach (@fileList) { next if -d; my $oldname = $_; s/Closed/Open/; rename $oldname, $_ or $_ = $oldname, warn $_, ' not renamed: ', $!; }
After Compline,
Zaxo
In reply to Re: Shorter/Better way to rename list of files in a directory
by Zaxo
in thread Shorter/Better way to rename list of files in a directory
by Scrat
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |