【问题标题】:Perl: check existence of file with wildcardPerl:使用通配符检查文件是否存在
【发布时间】:2020-03-05 07:32:51
【问题描述】:

我正在尝试使用 -e 来检查文件是否存在,$name 是用户指定的任何输入,"_file_" 是固定的,* 可能是任何可能的。目前无法检测到该文件。

if (-e $name."_file_*.txt)
{
   do something;
}

【问题讨论】:

  • 你不能有通配符,它​​必须是一个特定的文件名
  • 您应该问自己以下问题:$name."_file_*.txt" 是代表一个文件还是多个文件? -e 只检查一个特定文件而不检查其他文件。 documentation
  • 是的,我知道 $name。"file*.txt" 在这种情况下指的是一个文件名。但我想搜索是否存在任何符合条件的文件。
  • 文件是否存在后打开?
  • 不,只是想检查一下是否存在

标签: perl


【解决方案1】:

为什么不使用glob()呢?

if (my @files = glob("\Q$name\E_file_*.txt")) {
  # do something
}

【讨论】:

  • @ikegami 当我看到你的名字here 哈哈 .. 谢谢!
  • 考虑到我已经回答的 Perl 问题的数量,并不是真的 :) "\Q...\E"quotemeta("...") 的缩写,它用斜杠(插值后)转义非单词字符。所以如果$namefoo bar,这将导致glob("foo\\ bar_file_*.txt") 而不是不正确的glob("foo bar_file_*.txt")
  • 不要在标量上下文中调用glob;如果您再次执行该行(例如,如果它在循环或子中),您会得到一些奇怪的行为。你可以使用if ( my @files = glob(...) ) { ... }
  • @ikegami 你的意思是当它到达终点时它会返回undef?我想这是有道理的
【解决方案2】:

这是我可以找到具有特定名称的现有文件的方法之一:

use strict;
use warnings;
use Cwd;

my $name = "Test";
my $curdir = getcwd();
my @txtfiles = glob "$curdir/*.txt";
foreach my $txtfile (@txtfiles)
{
    if($txtfile=~m/$name\_file\_(.*?)\.txt/)
    {
        print "Ok...\n";    
    }
    else {  next;  }
}

【讨论】:

  • 为什么不my @files = glob("$curdir/${name}_file_*.txt");?或者甚至只是say for glob("$curdir/${name}_file_*.txt");
  • 是的。有办法检查
  • 当您在$curdir 中查找文件时,它是多余的,可以省略。
【解决方案3】:

我建议你使用 File::Find 模块。

use strict;
use warnings;
use File::Find;

# this takes the function a reference and will be executed for each file in the directory.
find({ wanted => \&process, follow => 1 }, '/dir/to/search' );

sub process {
  my $filename = $_; 
  my $filepath = $File::Find::name;
  if( $filename=~m/$name\_file\_(.*?)\.txt/ ){
    # file exists and do further processing
  } else {
    # file does not exists
  }
}


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多