Perl:使用通配符检查文件是否存在

时间:2020-03-05 07:32:51

标签: perl

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

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

3 个答案:

答案 0 :(得分:6)

为什么不使用glob()

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

答案 1 :(得分:1)

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

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;  }
}

答案 2 :(得分:1)

我建议您使用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
  }
}


相关问题