我想要一个目录和所有电子邮件(* .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’),但你的重命名需要像’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);