如何在perl中检查文件是否存在于特定目录中?

如何在perl中检查文件是否存在于特定目录中?,perl,Perl,如何在perl中检查特定目录中是否存在特定文件? 检查绝对目录名是否为绝对文件名前缀的明显方法不起作用,因为有时绝对目录名类似于/a/b/c/ if (-e "/path/to/file/filename.txt") { print("file exists"); } ?的查找功能可用于: 节目 输出 如果您不知道可以使用的确切路径。它为您生成代码。要立即执行该命令,请执行以下操作: $ find2perl /path/to/dir -name filename.txt -exec ec

如何在perl中检查特定目录中是否存在特定文件? 检查绝对目录名是否为绝对文件名前缀的明显方法不起作用,因为有时绝对目录名类似于/a/b/c/

if (-e "/path/to/file/filename.txt") {
   print("file exists");
}

查找功能可用于:

节目 输出
如果您不知道可以使用的确切路径。它为您生成代码。要立即执行该命令,请执行以下操作:

$ find2perl /path/to/dir -name filename.txt -exec echo exists {} | perl
find2perl生成的代码
#/usr/bin/perl-w
eval'exec/usr/bin/perl-S$0${1+“$@”}
如果为0#$在某个壳下运行
严格使用;
使用File::Find();
#设置变量$File::Find::not_使用链接如果您使用的是AFS,
#因为AFS作弊。
#为了方便通缉电话,包括-eval语句:
使用变量qw/*name*dir*prune/;
*name=*文件::查找::名称;
*dir=*File::Find::dir;
*prune=*File::Find::prune;
次级通缉犯;
次级doexec($@);
使用Cwd();
我的$cwd=cwd::cwd();
#遍历所需的文件系统
文件::查找::查找({wanted=>\&wanted},'/path/to/dir');
出口
通缉犯{
/^文件名\.txt\z/s&&
doexec(0,'echo','exists','{}');
}
子doexec($@){
我的$ok=班次;
my@command=@;#复制,这样我们就不会尝试将s///别名复制到常量
对于我的$word(@command)
{$word=~s{}{$name}g}
如果($ok){
my$old=选择(标准输出);
$| = 1;
打印“@命令”;
选择($old);
返回0,除非=~/^y/;
}
chdir$cwd;#叹气
系统@命令;
chdir$File::Find::dir;
返回!$?;
}

由于我不知道文件的路径,因此无法使用。在已知目录中可能有另一个目录。啊,你的意思是在已知目录中包含的任何子目录中查找它?CPAN中有一个File::Find模块,它为您提供了这样一个功能:如果目录中有符号链接,那么它还会在其中搜索吗?abc15:上面的程序不遵循符号链接。但是,您可以将
follow
选项传递给
find
函数。请参阅
文件::查找的文档:
Found file 'foo' in directory 'a/b/c'                                                                  
$ find2perl /path/to/dir -name filename.txt -exec echo exists {} | perl
#! /usr/bin/perl -w
    eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
        if 0; #$running_under_some_shell

use strict;
use File::Find ();

# Set the variable $File::Find::dont_use_nlink if you're using AFS,
# since AFS cheats.

# for the convenience of &wanted calls, including -eval statements:
use vars qw/*name *dir *prune/;
*name   = *File::Find::name;
*dir    = *File::Find::dir;
*prune  = *File::Find::prune;

sub wanted;
sub doexec ($@);

use Cwd ();
my $cwd = Cwd::cwd();

# Traverse desired filesystems
File::Find::find({wanted => \&wanted}, '/path/to/dir');
exit;

sub wanted {
    /^filename\.txt\z/s &&
    doexec(0, 'echo','exists','{}');
}

sub doexec ($@) {
    my $ok = shift;
    my @command = @_; # copy so we don't try to s/// aliases to constants
    for my $word (@command)
        { $word =~ s#{}#$name#g }
    if ($ok) {
        my $old = select(STDOUT);
        $| = 1;
        print "@command";
        select($old);
        return 0 unless <STDIN> =~ /^y/;
    }
    chdir $cwd; #sigh
    system @command;
    chdir $File::Find::dir;
    return !$?;
}