15

我可以在 Perl 中做这样的事情吗?文件名的含义模式匹配并检查它是否存在。

    if(-e "*.file")
    {
      #Do something
    }

我知道要求系统列出存在的文件的更长解决方案;将其作为文件读取,然后推断文件是否存在。

4

3 回答 3

34

You can use glob to return an array of all files matching the pattern:

@files = glob("*.file");

foreach (@files) {
    # do something
}

If you simply want to know whether a file matching the pattern exists, you can skip the assignment:

if (glob("*.file")) {
    # At least one file matches "*.file"
}
于 2010-10-18T22:20:43.370 回答
1

在 Windows 上,我不得不使用File::Glob::Windows作为分隔反斜杠的 Windows 路径似乎不适用于 perl 的 glob。

于 2018-07-18T06:53:15.907 回答
0

在 *nix 系统上,我使用了以下方法,效果很好。

sub filesExist { return scalar ( my @x = `ls -1a 2> /dev/null "$_[0]"` ) }

它回复找到的匹配数,如果没有,则返回 0。使其易于在“if”条件中使用,例如:

if( !filesExist( "/foo/var/not*there.log" ) &&
    !filesExist( "/foo/var/*/*.log" ) &&
    !filesExist( "/foo/?ar/notthereeither.log" ) )
{
    print "No matches!\n";
} else {
    print "Matches found!\n";
}

您可以使用的确切模式将取决于您的 shell 支持的内容。但大多数 shell 支持使用 '*' 和 '?' - 在我见过的任何地方,它们的意思都是一样的。当然,如果您删除了对“标量”函数的调用,它将返回匹配项——这对于查找这些变量文件名很有用。

于 2013-09-30T18:32:11.760 回答