Perl glob 在尝试匹配特定文件类型时返回误报

Perl glob returning false positive when trying to match specific file types

我正在尝试使用 glob 匹配目录中的“program.log”或“program.log.gz”或两者,但 glob 将两个字符串都返回给@array,无论它们是否存在.

我做到了

@array = glob ("$dir/program.{log,log.gz}");

现在@array 包含

$dir/program.log
$dir/program.log.gz

不管它们是否真的存在。

似乎 glob 只是扩展字符串并将其传递给@array,而不管该文件是否实际存在。这是 glob 的预期行为吗?如果是这样,我如何只将存在的文件名传递给@array?

这是 glob 的记录行为:

If non-empty braces are the only wildcard characters used in the glob, no filenames are matched, but potentially many strings are returned. For example, this produces nine strings, one for each pairing of fruits and colors:

my @many = glob "{apple,tomato,cherry}={green,yellow,red}";

如果只想将现有文件传递给数组,可以使用 grep 和文件测试,例如 -e (exists)

my @files = grep -e, glob ("$dir/program.{log,log.gz}");