我想要一个目录,对于所有电子邮件 (*.msg) 文件,删除开头的“RE”。我有以下代码,但重命名失败。
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";
}
最佳答案
如果您的 ./emails
目录包含以下文件:
1.msg
2.msg
3.msg
那么你的
@files
看起来像 ('.', '..', '1.msg', '2.msg', '3.msg')
但是你的 rename
想要像 'emails/1.msg'
这样的名字, 'emails/2.msg'
等。所以你可以 chdir
重命名前:chdir('emails');
for (@files) {
#...
}
您可能想查看
chdir
返回值也是。或者自己添加目录名称:
rename('emails/' . $old, 'emails/' . $_) or print "Error renaming $old: $!\n";
# or rename("emails/$old", "emails/$_") if you like string interpolation
# or you could use map if you like map
您可能希望使用
grep
将目录读取和过滤结合起来。 :my @files = grep { /^RE .+msg$/ } readdir(DIR);
甚至这个:
opendir(DIR, 'emails') or die "Cannot open directory";
for (grep { /^RE .+msg$/ } readdir(DIR)) {
(my $new = $_) =~ s/^RE //;
rename("emails/$_", "emails/$new") or print "Error renaming $_ to $new: $!\n";
}
closedir(DIR);
关于perl - 使用 Perl 重命名目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8450812/