2010-08-04 38 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] 
}