检查文件是否存在(Perl)
如何编写perl脚本来检查文件是否存在 例如,如果我想检查$file是否存在于$location中 目前我正在使用一个冗长的子例程(见下文),我确信有一种更简单的方法可以做到这一点检查文件是否存在(Perl),perl,Perl,如何编写perl脚本来检查文件是否存在 例如,如果我想检查$file是否存在于$location中 目前我正在使用一个冗长的子例程(见下文),我确信有一种更简单的方法可以做到这一点 # This subroutine checks to see whether a file exists in /home sub exists_file { @list = qx{ls /home}; foreach(@list) { chop($_); if ($_ eq $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;
}
}
使用
-e
操作符:
if (-e "$location/$file") {
print "File $location/$file exists.\n";
}
不过,您可能希望使用比串联更健壮的方法将
$location
与$file
连接起来。另请参阅文档(随Perl提供)或。是,假设$your_file
是您要检查的文件(类似于/home/dude/file.txt):
你可以用
if(-e $your_file){
print "I'm a real life file!!!"
}
else{
print "File does not exist"
}
把它叫做,例如
if ( file_exists( 'foobar' ) ) { ... } # check if /home/foobar exists
其他人的解决方案将“无法确定文件是否存在”误称为“文件不存在”。以下内容不存在该问题:
sub file_exists {
my ($qfn) = @_;
my $rv = -e $qfn;
die "Unable to determine if file exists: $!"
if !defined($rv) && !$!{ENOENT};
return $rv;
}
如果您还想检查它是否是普通文件(即不是目录、符号链接等)
文档:还有一个
-f
操作符用于检查它是否是文件,还有一个-d
操作符用于检查目录。还有其他的。您可以在手册页的摘录中看到一个详尽的列表。在函数中使用子例程有点过火。=)<代码>如果…,则返回1最好的样式是错误的,最坏的样式是反模式的。只需返回布尔表达式本身<代码>返回-f…@ikegami有趣。但那是很多陈词滥调。在cpan上找不到传递支票的模块。你知道其中一个吗?@Zaid,你知道得更清楚!:)<代码>%代码>输入
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;
}