2010-08-04 34 views
1

存在例如:如何找到文件中的Perl

#!/usr/bin/perl 
my @arr = ('/usr/test/test.*.con'); 
my $result = FileExists(\@arr); 

print $result ; 

sub FileExists { 
    my $param = shift; 
    foreach my $file (@{$param}) { 
     print $file ; 
     if (-e $file) { 
      return 1; 
     } 
    } 
    return 0; 
} 

則返回0。但是,我要找到所有野生人物太...如何解決這個問題?

+0

我不知道,如果你在Windows或Unix的時候,但在Unix外殼通常手柄通配符擴展。因此,如果您運行'myprog.pl * .txt',您的程序將在目錄中看到目錄中的.txt文件列表(如果有的話)。爲了避免這種擴展,你需要用引號將參數括起來:'myprog.pl「* .txt」' – Arkadiy 2010-08-04 14:05:59

回答

10

-e無法處理文件的大小。這條線

my @arr = ('/usr/test/test.*.con'); 

更改爲

my @arr = glob('/usr/test/test.*.con'); 

要先擴大glob模式,然後檢查匹配的文件所有腦幹。但是,由於glob只會返回與該模式匹配的現有文件,因此所有文件都將存在。

+0

也許他們想要做的只是檢查glob是否產生任何結果,即:我的@arr = glob(...);如果@arr> 0,則打印「是」; – siride 2010-08-04 14:06:24

+2

因爲glob實現了shell擴展規則,所以在某些情況下可以返回不存在的文件。例如'glob('no {file,where}')'返回兩個項目,並且不存在於我的文件系統中。 – 2010-08-04 19:16:24

2

您需要使用glob()來獲取文件列表。

此外,我不知道爲什麼你傳遞數組作爲參考,當subs採用數組默認情況下。你可以更容易地這樣寫:

my @arr = (...); 
my $result = FileExists(@arr); 

sub FileExists { 
    foreach my $file (@_) { 
     ... 
    } 
    return 0; 
} 
2

如果你想處理glob模式,使用glob運營商將其展開。然後測試所有路徑,將結果存儲在散列中,然後返回散列。

sub FileExists { 
    my @param = map glob($_) => @{ shift @_ }; 

    my %exists; 
    foreach my $file (@param) { 
     print $file, "\n"; 
     $exists{$file} = -e $file; 
    } 

    wantarray ? %exists : \%exists; 
} 

然後說,你把它作爲

use Data::Dumper; 

my @arr = ('/tmp/test/test.*.con', '/usr/bin/a.txt'); 
my $result = FileExists(\@arr); 

$Data::Dumper::Indent = $Data::Dumper::Terse = 1; 
print Dumper $result; 

採樣運行:

$ ls /tmp/test 
test.1.con test.2.con test.3.con 

$ ./prog.pl 
/tmp/test/test.1.con 
/tmp/test/test.2.con 
/tmp/test/test.3.con 
/usr/bin/a.txt 
{ 
    '/tmp/test/test.3.con' => 1, 
    '/tmp/test/test.1.con' => 1, 
    '/usr/bin/a.txt' => undef, 
    '/tmp/test/test.2.con' => 1 
}
0

使用水珠(),您將有外殼擴展,並使用shell通配符的文件可以被檢索正如其他人所指出的那樣。

和公正的情況下,你會發現它有用,因爲「all_files_exist」多一點簡潔的功能可能是

sub all_files_exist { 
    # returns 1 if all files exist and 0 if the number of missing files (!-e) 
    # captured with grep is > 0. 
    # This method expect an array_ref as first and only argument 

    my $files=shift; 
    return (grep {!-e $_} @$files)>0? 0 : 1; 
} 

sub non_existing_files { 
    # or you can capture which ones fail, and print with 
    # print join("\n", @(non_existing_files($files))) 
    my $files = shift; 
    return [grep {!-e $_} @$files] 
}