$dir = "/home/naveen/mp3tag/testfolder";
opendir(DMP3, $dir) || die("Cannot open directory");
@files= readdir(DMP3;
foreach $f (@files)
{
unless ( ($f eq ".") || ($f eq "..") )
{
$oldfile = $f;
$newfile = $f;
$newfile =~ s/ /_/g;
print "Old file: $oldfile \t";
print "New file: $newfile";
print "\n";
rename ("$oldfile", "$newfile") or warn "Couldn't rename $oldfile to $newfile !\n";
}
}
I’m writing a simple program to add underscores to an existing file and rename it. This is how far ive gotten with the code. However its not able to rename the file and gives me a warning and i’m not sure where the mistake is.
Also when i tried the same line on the cmd line I get the following error msg.
$ rename Jacques\ Greene\ -\ Clark\ \(Original\ Mix\).mp3 JG - C.mp3
Bareword "mp3" not allowed while "strict subs" in use at (eval 1) line 1.
$ rename Jacques\ Greene\ -\ Clark\ \(Original\ Mix\) JG - C
Can't locate object method "Original" via package "Mix" (perhaps you forgot to load "Mix"?) at (eval 1) line 1.
You’re trying to rename all the files in the directory, not just one file. The error could be a great many things, since you did not mention it, I could only guess.
renameis, as I recall, a bit wonky, and usingmovefrom File::Copy is a safer bet. Also, you might want to avoid renaming directories. Using a more intuitive interface would probably not be a bad idea either.One of your biggest mistakes is not using
use strict; use warnings;. The amount of trouble you bring on yourself by leaving these out cannot be underestimated.Usage:
So, as long as you give a proper glob as argument, your script will only affect those files. You can add more checks to make it stricter.
If that commandline attempt of yours is meant to be with using the tool from /usr/bin/rename, I would hazard a guess that your error can simply be avoided by using quotes.