Using Perl to change file names
The previous tip showed how you can change filenames in a given directory uisng the command line. If you need to use perl to programatically change file names you can use the rename perl function. Often times I need to iterate through a directory and change names of files based on a given condition. Here is an example of using the rename function ($sourcepath is set to the absolute path of the directory you want to use):
foreach my $file(@files){
$newname = $file;
if ($newname =~ /^$story/){
$newname =~ s/$story/$newstoryname/i;
rename “$sourcepath”.”$subfile”, “$sourcepath”.”$newname” or warn “rename $sourcepath$file to $sourcepath$newname failed: $!\n”;
print “$sourcepath”.”$newname”.”\n”;
}
The above example assumes that the @files array has been poplulated through a readdir command. You could do it like this:
opendir (SOURCEDIR, “$sourcepath”) or die “Can’t open sourcedir ” . $!;
@comprehensivedir = readdir SOURCEDIR;
foreach $file(@comprehensivedir){
if (-f “$sourcepath”.”$file”){
push (@files, $file) unless $file =~ /^\./;
}
the if (-f is the file switch. I’m only pushing files in the array, not directories. the unless statement will only push the file if it doesn’t start with a period. That way you don’t get hidden files pushed onto your array.