2014-11-21 101 views
0

當前在perl腳本中,我使用glob函數來獲取具有特定擴展名的文件列表。如何從perl中的文件夾獲取具有特定擴展名的文件名

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

是否有任何替代glob的,以獲得具有特定擴展名的文件的文件夾列表?如果有,請給我一些例子?謝謝

+1

爲什麼'glob'不夠好? – 2014-11-21 07:36:02

+0

你可以使用正則表達式。 – ProfGhost 2014-11-21 07:36:49

+0

glob有時會使用較低版本的perl運行時失敗。 – DevLion 2014-11-21 08:13:22

回答

1

是的,有更復雜的方法,如opendir,readdir和一個正則表達式過濾器。他們也會給你的隱藏文件(或點文件):

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

我在Windows環境中運行perl腳本。上面的代碼不適用於腳本。 – DevLion 2014-11-21 10:33:32

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; 
+0

我在Windows環境中運行perl腳本。上面的代碼不適用於腳本。 – DevLion 2014-11-21 10:32:59

+0

您能否檢查另一種格式.... – ssr1012 2014-11-21 12:31:50

+0

謝謝你的工作。它也檢索子文件夾中的文件。我們怎麼才能使這個只在主文件夾中檢索我們已經打好的文件? – DevLion 2014-11-21 13:33:20

相關問題