如何从perl中的文件夹中获取具有特定扩展名的文件名

时间:2014-11-21 07:25:30

标签: perl search glob

目前在perl脚本中,我使用glob函数来获取具有特定扩展名的文件列表。

my @filearray = glob("$DIR/*.abc $DIR/*.llc");

是否有替代glob的方法,从文件夹中获取具有特定扩展名的文件列表?如果是这样,请提供一些例子?谢谢

2 个答案:

答案 0 :(得分:1)

是的,有更复杂的方法,例如opendirreaddir和正则表达式过滤器。他们还会给你隐藏的文件(或dotfiles):

opendir DIR, $DIR or die $!;
my @filearray = grep { /\.(abc|llc)$/ } readdir DIR;
closedir DIR;

答案 1 :(得分:0)

#Using:
opendir(DIR, $dir) || die "$!";
my @files = grep(/\.[abc|lic]*$/, readdir(DIR));
closedir(DIR);

#Reference: CPAN
use Path::Class;  # Exports dir() by default

my $dir = dir('foo', 'bar');       # Path::Class::Dir object
my $dir = Path::Class::Dir->new('foo', 'bar');  # Same thing

my $file = $dir->file('file.txt'); # A file in this directory
my $handle = $dir->open;
while (my $file = $handle->read)
{
    $file = $dir->file($file);  # Turn into Path::Class::File object
    ...
}

#Reference: Refered: http://accad.osu.edu/~mlewis/Class/Perl/perl.html#cd
# search for a file in all subdirectories
#!/usr/local/bin/perl
if ($#ARGV != 0) {
    print "usage: findfile filename\n";
    exit;
}

$filename = $ARGV[0];

# look in current directory
$dir = getcwd();
chop($dir);
&searchDirectory($dir);

sub searchDirectory
{
    local($dir);
    local(@lines);
    local($line);
    local($file);
    local($subdir);

    $dir = $_[0];

    # check for permission
    if(-x $dir)
{
    # search this directory
    @lines = `cd $dir; ls -l | grep $filename`;
    foreach $line (@lines)
    {
        $line =~ /\s+(\S+)$/;
        $file = $1;
        print "Found $file in $dir\n";
    }
    # search any sub directories
    @lines = `cd $dir; ls -l`;
    foreach $line (@lines)
    {
        if($line =~ /^d/)
        {
            $line =~ /\s+(\S+)$/;
            $subdir = $dir."/".$1;
            &searchDirectory($subdir);
        }
    }
    }
}

请尝试另一个:

use Cwd;
use File::Find;
my $dir = getcwd();
my @abclicfiles;

find(\&wanted, $dir);
sub wanted
{
    push(@abclicfiles, $File::Find::name) if($File::Find::name=~m/\.(abc|lic)$/i);
}
print join "\n", @abclicfiles;

这是从用户获取的目录:

print "Please enter the directory: ";
my $dir = <STDIN>;
chomp($dir);

opendir(DIR, $dir) || die "Couldn't able to read dir: $!";
my @files = grep(/\.(txt|lic)$/, readdir(DIR));
closedir(DIR);
print join "\n", @files;