I’d like to take a directory and for all email (*.msg) files, remove the ‘RE ‘ at the beginning. I have the following code but the rename fails.
opendir(DIR, 'emails') or die "Cannot open directory";
@files = readdir(DIR);
closedir(DIR);
for (@files){
next if $_ !~ m/^RE .+msg$/;
$old = $_;
s/RE //;
rename($old, $_) or print "Error renaming: $old\n";
}
If your
./emailsdirectory contains these files:then your
@fileswill look something like('.', '..', '1.msg', '2.msg', '3.msg')but yourrenamewants names like'emails/1.msg','emails/2.msg', etc. So you canchdirbefore renaming:You’d probably want to check the
chdirreturn value too.Or add the directory names yourself:
You might want to combine your directory reading and filtering using
grep:or even this: