perlperlscript

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


Hi I am tring to calculate size of perticular directory using below code but i want to search string as DIR0* to list all directories named DIR01, DIR02. How can i implement this?

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

Solution

  • update: 2015-04-27-17:25:24 This is how the genereated regex might look

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

    And this is how you'd use it in your program

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

    oldanswer: use the 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
    

    and the verbose version that doesn't build a list of filenames in memory

    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' );