使用 * 和 _ 使用 $File::Find::dir 计算目录中的文件

Using * and _ to calculate files in directory using $File::Find::dir

您好,我正在尝试使用以下代码计算特定目录的大小,但我想搜索字符串作为 DIR0* 以列出所有名为 DIR01、DIR02 的目录。我该如何实施?

if ($File::Find::dir =~ m/^(.*)$search/) {
$size += -s ;
}

更新:2015-04-27-17:25:24 这就是生成的正则表达式的样子

$ perl -e"use Text::Glob qw/ glob_to_regex /; print glob_to_regex(qw/ thedir0* /);
(?^:^(?=[^\.])thedir0[^/]*$)

这就是您在程序中使用它的方式

use Text::Glob qw/ glob_to_regex /;
my $searchRe = glob_to_regex(qw/ thedir0* /);
...
if( $File::Find::dir =~ m{$searchRe} ){
    $size += -s ;
}

旧答案: 使用 rule its got globbing powers courtesy of Text::Glob#glob_to_regex

$ touch thedir0 thedir1 thedir5 thedir66

$ findrule . -name thedir*
thedir0
thedir1
thedir5
thedir66

$ findrule . -name thedir0*
thedir0

$ perl -e"use File::Find::Rule qw/ find rule/; print for find( qw/ file name thedir0* in . /); "
thedir0

$ perl -e"use File::Find::Rule qw/ find rule/; my $size= 0; $size += -s $_ for find( qw/ file name thedir0* in . /); print $size "
0

以及不在内存中构建文件名列表的详细版本

use File::Find::Rule qw/ find rule /;
my $size = 0;
rule(
    directory =>
    maxdepth => 1 ,
    name => [ 'thedir0*', ],
    exec => sub {
        ## my( $shortname, $path, $fullname ) = @_;
        $size += -s _; ## or use $_
        return !!0; ## means discard filename
    },
)->in( 'directory' );