如何使用Perl在具有特定名称模式的目录下列出文件?

如何使用Perl在具有特定名称模式的目录下列出文件?,perl,directory,Perl,Directory,我有一个目录/var/spool,其中有一个名为 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 等等 我需要这些文件,然后打开每个单独的文件修改头和正文。这部分我已经有了,但我需要第一部分 我正在尝试: dir = "/var/spool"; opendir ( DIR, $dir ) || die "No pude abrir el directorio $dirname\n"; while( (

我有一个目录
/var/spool
,其中有一个名为

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 等等

我需要这些文件,然后打开每个单独的文件修改头和正文。这部分我已经有了,但我需要第一部分

我正在尝试:

dir = "/var/spool";

opendir ( DIR, $dir ) || die "No pude abrir el directorio $dirname\n";
while( ($filename = readdir(DIR))){
    @directorios1 = `ls -l "$dir/$filename"`;
    print("@directorios1\n");
}
closedir(DIR);
但是不能按我需要的方式工作。

您可以使用。

用于遍历目录树。

尝试以下操作:

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
如其他人所述,使用:


对于固定级别的目录,有时它比File::Find更易于使用:

while (my $file = </var/spool/[a-z]/user/*/*>) {
  print "Processing $file\n";
}
while(我的$file=){
打印“正在处理$file\n”;
}

人们不断推荐File::Find,但另一个让它变得简单的是my,它为您提供了方便的功能:

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

您甚至不需要使用
File::Find::Closures
。我编写了这个模块,这样您就可以取出您想要的子例程并将其粘贴到您自己的代码中,也许可以对其进行调整以获得所需的内容。

您好,我已经尝试过了。。我所得到的是这个错误。。。main::browse()调用太早,无法在------子浏览($){my$dir=$\u0];\35;附加一个/if-missing if($path!~/\/$/){$path.='/'}if($dir!~/\/$){$dir.='/'}循环检查目录中包含的文件,如果是我的$eachFile(glob($path.'.')){如果是我的$eachFile(glob($dir.')){(-d$eachFile){#递归浏览目录($eachFile)}其他{print$eachFile;}}}}}浏览-----对不起,但是..我做错了什么?让我猜猜:C是你最喜欢的语言?不要使用原型。不要重新发明轮子。非常感谢你的帮助!!这很好…所以…现在:,使用…print$File::Find::name,“\n”我得到了我所需要的…是否有一种方法将其发送到一个变量,每行一个变量,以便处理修改消息的每个文件?谢谢…Michael-
while (my $file = </var/spool/[a-z]/user/*/*>) {
  print "Processing $file\n";
}
 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->();