2011-12-21 180 views
3

如何編寫perl腳本來檢查文件是否存在?檢查文件是否存在(Perl)

例如,如果我想檢查$ location中是否存在$ file。

目前我使用冗長的子程序(見下文),我確信有一個更簡單的方法來做?

# This subroutine checks to see whether a file exists in /home 
sub exists_file { 
    @list = qx{ls /home}; 
    foreach(@list) { 
    chop($_); 
    if ($_ eq $file) { 
    return 1; 
    } 
} 

回答

11

使用-e操作:

if (-e "$location/$file") { 
    print "File $location/$file exists.\n"; 
} 

你可能想使用一些更強大的比串接與$file加入$location,雖然。另請參閱File::Spec(包含在Perl中)或Path::Class的文檔。

+2

還有一個'-f'運算符用於檢查目錄是文件還是'-d'。還有其他人。您可以在[perlfunc](http://perldoc.perl.org/functions/-X.html)手冊頁的摘錄中看到詳盡的列表。 – zostay 2011-12-21 03:11:34

1

是,假設$your_file是要檢查的(像/home/dude/file.txt)文件:

你可以使用

if(-e $your_file){ 
    print "I'm a real life file!!!" 
} 
else{ 
    print "File does not exist" 
} 
1
sub file_exists { 
    return 1 if -f '/home/' . $_[0]; 
} 

,並調用它像例如

if (file_exists('foobar')) { ... } # check if /home/foobar exists 
+0

對於函數使用子例程有些矯枉過正。 =) – TLP 2011-12-21 03:52:39

+3

'返回1如果...'最壞的風格,最壞的反模式。只需返回布爾表達式本身! 'return -f ...' – daxim 2011-12-21 17:47:11

3

其他人的解決方案誤報「無法確定文件是否存在」爲「文件不存在」。下列不從問題的困擾:

sub file_exists { 
    my ($qfn) = @_; 
    my $rv = -e $qfn; 
    die "Unable to determine if file exists: $!" 
     if !defined($rv) && !$!{ENOENT}; 
    return $rv; 
} 

如果你還需要檢查它是否是一個純文本文件(即不是目錄,符號鏈接等),或者沒有,

sub is_plain_file { 
    my ($qfn) = @_; 
    my $rv = -f $qfn; 
    die "Unable to determine file type: $!" 
     if !defined($rv) && !$!{ENOENT}; 
    return $rv; 
} 

文檔: -X

+1

什麼是'$!{ENOENT}'? – Zaid 2011-12-21 07:23:34

+0

@ikegami有趣。但這是很多樣板。在cpan上沒有找到提供支票的模塊。你知道嗎? – 2011-12-21 11:02:32

+1

@Jan Hartung,也許autodie? – ikegami 2011-12-21 19:15:49