2010-06-25 150 views
0

我使用这个代码来处理我的文件夹和文件有两个替补:用于与扩展文件名的文件夹名称仅
“子文件”
“子文件夹”只有Perl的重命名文件夹和文件文件::查找

但我意识到“子文件夹”在重命名过程中与我的文件扩展混淆。

如何区分进程彼此,或者什么是告诉“子文件夹”重命名“名称”没有扩展名和“子文件”重命名“名称”与externsion的智能方式?

find(\&folders, $dir_source); 
sub folders { 
    my $fh = $File::Find::dir; 
    my $artist = (File::Spec->splitdir($fh))[3];   

    if (-d $fh) { 
     my $folder_name = $_; 

     # some substitution 

     rename $folder_name, $_; 
    } 
} 


find(\&files, $dir_source); 
sub files { 
    /\.\w+$/ or return; 
    my $fn = $File::Find::name; 

    my ($genre, $artist, $boxset, $album, $disc); 
    if ($fn =~ /Singles/ or $fn =~ /Box Set/) { 
     ($genre, $artist, $boxset, $album, $disc) = (File::Spec->splitdir($fn))[2..6]; 
    } 
    else { 
     ($genre, $artist, $album, $disc) = (File::Spec->splitdir($fn))[2..5]; 
    } 

    if (-e $fn) { 
     my $file_name = $_; 

     # some substitution 

     rename $file_name, $_; 
    } 
} 

回答

1

File :: Find :: find()调用每个文件和文件夹的子集。如果你只想影响文件夹,那么忽略文件:

而你需要调用finddepth()而不是find(),因为你正在改变目录名称(你要重命名“更深”更“浅”之前的目录)。

finddepth(sub { 
    return unless -d; 

    (my $new = $_) =~ s/this/that/ or return; 
    rename $_, $new or warn "Err renaming $_ to $new in $File::Find::dir: $!"; 
}, "."); 

替代多个换人:

finddepth(sub { 
    return unless -d; 

    my $new = $_; 
    for ($new) { 
    s/this/that/; 
    s/something/something_else/; 
    } 
    return if $_ eq $new; 

    rename $_, $new or warn "Err renaming $_ to $new in $File::Find::dir: $!"; 
}, "."); 

而且在文件子,我会做的第一条语句:

return unless -f; 
+0

你的建议是真棒毫无疑问。我只有很难通过几个 my $ new; ($ new = $ _)=〜s /某事/其他/返回; ,因为它只适用于一个。 – thebourneid 2010-06-25 16:29:08

+0

不确定你的意思。你想对同一个变量做几个s ///,如果它们中的任何一个改变了值,就重命名它们? – runrig 2010-06-25 16:36:29

+0

是的。在我的完整代码中,我有10-15秒///,并且如果有任何人在ANYWHERE遇到任何文件夹 - 重命名。但是我猜想当添加“或者返回”时 - 如果没有满足要求,它会停止处理。我对么? – thebourneid 2010-06-25 16:43:32