检查文件是否存在(Perl)

时间:2011-12-21 03:03:54

标签: 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;
  }
}

4 个答案:

答案 0 :(得分:11)

使用-e运算符:

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

但是,您可能希望使用比连接更强大的功能来将$location加入$file。另请参阅File::Spec(包含在Perl中)或Path::Class的文档。

答案 1 :(得分: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

答案 2 :(得分:1)

是的,假设$your_file是您要检查的文件(类似于/home/dude/file.txt):

你可以使用

if(-e $your_file){
   print "I'm a real life file!!!"
}
else{
   print "File does not exist"
}

答案 3 :(得分:1)

sub file_exists { 
    return 1 if -f '/home/' . $_[0];
}

并称之为例如。

if ( file_exists( 'foobar' ) ) { ... }  # check if /home/foobar exists
相关问题