How can I list files under a directory with a specific name pattern using Perl?

后端 未结 6 838
长发绾君心
长发绾君心 2021-01-07 12:15

I have a directory /var/spool and inside that, directories named

a  b  c  d  e  f  g  h i  j  k  l  m  n  o  p q  r  s  t  u  v  x  y z

An

相关标签:
6条回答
  • 2021-01-07 12:47

    People keep recommending File::Find, but the other piece that makes it easy is my File::Find::Closures, which provides the convenience functions for you:

     use File::Find;
     use File::Find::Closures qw( find_by_regex );
    
     my( $wanted, $reporter ) = find_by_regex( qr/^\d+\.\z/ );
    
     find( $wanted, @directories_to_search );
    
     my @files = $reporter->();
    

    You don't even need to use File::Find::Closures. I wrote the module so that you could lift out the subroutine you wanted and paste it into your own code, perhaps tweaking it to get what you needed.

    0 讨论(0)
  • 2021-01-07 12:49

    Use File::Find to traverse a directory tree.

    0 讨论(0)
  • As others have noted, use File::Find:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use File::Find;
    
    find(\&find_emails => '/var/spool');
    
    sub find_emails {
        return unless /\A[0-9]+[.]\z/;
        return unless -f $File::Find::name;
    
        process_an_email($File::Find::name);
        return;
    }
    
    sub process_an_email {
        my ($file) = @_;
        print "Processing '$file'\n";
    }
    
    0 讨论(0)
  • 2021-01-07 12:56

    You can use File::Find.

    0 讨论(0)
  • 2021-01-07 12:59

    Try this:

    sub browse($);
    
    sub browse($)
    {    
        my $path = $_[0];
    
        #append a / if missing
        if($path !~ /\/$/)
        {
            $path .= '/';
        }
    
        #loop through the files contained in the directory
        for my $eachFile (glob($path.'*')) 
        {
    
            #if the file is a directory
            if(-d $eachFile) 
            {
                #browse directory recursively
                browse($eachFile);
            } 
            else 
            {
               # your file processing here
            }
        }   
    }#browse
    
    0 讨论(0)
  • 2021-01-07 13:09

    For a fixed level of directories, sometimes it's easier to use glob than File::Find:

    while (my $file = </var/spool/[a-z]/user/*/*>) {
      print "Processing $file\n";
    }
    
    0 讨论(0)
提交回复
热议问题