【问题标题】:Checking existence of a file given a directory format in perl在 perl 中检查给定目录格式的文件是否存在
【发布时间】:2010-12-13 12:23:56
【问题描述】:

我正在努力寻找一种遍历目录树以检查多个目录中是否存在文件的方法。我正在使用 Perl,我只能使用 File::Find,因为我无法为此安装任何其他模块。

这是我要遍历的文件系统的布局:

汽车/本田/思域/Setup/config.txt 汽车/本田/探路者/Setup/config.txt 汽车/丰田/卡罗拉/Setup/config.txt 汽车/丰田/Avalon/Setup/

请注意,最后一个安装文件夹缺少config.txt 文件。

编辑:此外,在每个安装文件夹中还有许多其他文件,这些文件因安装文件夹而异。确实没有任何单个文件可供搜索以进入 Setup 文件夹本身。

因此,您可以看到文件路径保持不变,除了 make 和 model 文件夹。我想找到所有的 Setup 文件夹,然后检查该文件夹中是否有 config.txt 文件。

一开始我用File::Find下面的代码

my $dir = '/test/Cars/';
find(\&find_config, $dir);

sub find_config {
    # find all Setup folders from the given top level dir
    if ($File::Find::dir =~ m/Setup/) {
       # create the file path of config.txt whether it exists or not, well check in the next line 
       $config_filepath = $File::Find::dir . "/config.txt";
       # check existence of file; further processing
        ...
   }
}

您可以明显看到尝试使用$File::Find::dir =~ m/Setup/ 时的缺陷,因为它会为Setup 文件夹中的每个文件返回一个命中。有没有办法使用-d 或某种目录检查而不是文件检查? config.txt 并不总是在文件夹中(如果它不存在,我将需要创建它)所以我不能真正使用像 return unless ($_ =~ m/config\.txt/) 这样的东西,因为我不知道它是否存在。

我正在尝试找到一种方法来使用 return unless ( <is a directory> and <the directory has a regex match of m/Setup/>) 之类的东西。

也许File::Find 不是解决此类问题的正确方法,但我已经搜索了一段时间,但在使用目录名而不是文件名方面没有任何好的线索。

【问题讨论】:

  • 为什么不能安装其他模块?
  • 我犹豫要不要使用任何其他模块,因为要获得批准在生产机器上使用它们的过程很长。

标签: perl file find directory


【解决方案1】:

File::Find 也可以查找目录名称。你想检查 when $_ eq 'Setup' (注意:eq,不是你的正则表达式,它也会匹配 XXXSetupXXX),然后查看目录中是否有 config.txt 文件(-f "$File::Find::name/config.txt")。如果您想避免抱怨名为 Setup 的文件,请检查找到的“Setup”是否为带有-d 的目录。

【讨论】:

    【解决方案2】:

    我正在尝试找到一种方法来使用 return unless ( <is a directory> and <the directory has a regex match of m/Setup/>) 之类的东西。

    use File::Spec::Functions qw( catfile );
    
    my $dir = '/test/Cars/';
    
    find(\&find_config, $dir);
    
    sub find_config {
        return unless $_ eq 'Setup' and -d $File::Find::name;
        my $config_filepath = catfile $File::Find::name => 'config.txt';
        # check for existence etc
    
    }
    

    【讨论】:

    • 非常感谢。 ysth 让我走上了正确的道路,而你几乎把一切都说清楚了。
    猜你喜欢
    • 2017-12-16
    • 2016-02-01
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 2017-07-14
    • 2019-02-24
    • 1970-01-01
    相关资源
    最近更新 更多