如何从特定目录中获取具有特定扩展名的所有文件的列表?

Che*_*eso 12 directory perl

我正在使用此代码获取特定目录中所有文件的列表:

opendir DIR, $dir or die "cannot open dir $dir: $!";
my @files= readdir DIR;
closedir DIR;
Run Code Online (Sandbox Code Playgroud)

如何修改此代码或向其添加内容以便它只查找文本文件并仅加载带有文件名前缀的数组?

示例目录内容:

.
..
923847.txt
98398523.txt
198.txt
deisi.jpg
oisoifs.gif
lksdjl.exe
Run Code Online (Sandbox Code Playgroud)

示例数组内容:

files[0]=923847 
files[1]=98398523
files[2]=198
Run Code Online (Sandbox Code Playgroud)

Woo*_*ble 11

my @files = glob "$dir/*.txt";
for (0..$#files){
  $files[$_] =~ s/\.txt$//;
}
Run Code Online (Sandbox Code Playgroud)


cat*_*alk 5

改变一行就足够了:

my @files= map{s/\.[^.]+$//;$_}grep {/\.txt$/} readdir DIR;
Run Code Online (Sandbox Code Playgroud)


Bra*_*ert 5

如果你可以使用 Perl 5.10 的新特性,我会这样写。

use strict;
use warnings;
use 5.10.1;
use autodie; # don't need to check the output of opendir now

my $dir = ".";

{
  opendir my($dirhandle), $dir;
  for( readdir $dirhandle ){ # sets $_
    when(-d $_ ){ next } # skip directories
    when(/^[.]/){ next } # skip dot-files

    when(/(.+)[.]txt$/){ say "text file: ", $1 }
    default{
      say "other file: ", $_;
    }
  }
  # $dirhandle is automatically closed here
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您有非常大的目录,则可以使用while循环。

{
  opendir my($dirhandle), $dir;
  while( my $elem = readdir $dirhandle ){
    given( $elem ){ # sets $_
      when(-d $_ ){ next } # skip directories
      when(/^[.]/){ next } # skip dot-files

      when(/(.+)[.]txt$/){ say "text file: ", $1 }
      default{
        say "other file: ", $_;
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)