in reply to Shorter/Better way to rename list of files in a directory
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Shorter/Better way to rename list of files in a directory
by Joost (Canon) on Jun 02, 2006 at 10:14 UTC | |
by Zaxo (Archbishop) on Jun 02, 2006 at 10:21 UTC | |
by Scrat (Monk) on Jun 02, 2006 at 11:17 UTC | |
by vek (Prior) on Jun 02, 2006 at 20:06 UTC | |
|
Re^2: Shorter/Better way to rename list of files in a directory
by Scrat (Monk) on Jun 02, 2006 at 08:43 UTC |