为什么我不能在 Perl 的菱形运算符中使用 typeglob?

Why can't I use a typeglob in the diamond operator in Perl?

通常裸字作为文件句柄或变量保存文件句柄可以放在 <> 运算符中以引用文件,但 NOT 从 typeglob 中提取的文件句柄作为最后一个下面一行显示。为什么它不起作用,因为最后一个案例也引用了一个文件句柄?

open FILE, 'file.txt';
my $myfile = *FILE{IO};
print <$myfile>;
print <*FILE{IO}>; # this line doesn't work.

<>readline() 的快捷方式,它接受简单的标量或裸词,即。 <FILE>。对于更复杂的表达式,你必须更明确,

print readline *FILE{IO};

否则会被解释为glob()

perl -MO=Deparse -e 'print <*FILE{IO}>;'

use File::Glob ();
print glob('*FILE{IO}');

perlop中说:

If what's within the angle brackets is neither a filehandle nor a simple scalar variable containing a filehandle name, typeglob, or typeglob reference, it is interpreted as a filename pattern to be globbed ...

因为我们希望能够这样说:

foreach (<*.c>) {
  # Do something for each file that matches *.c
}

perl 无法将“*”解释为类型团。

如另一个答案中所述,您可以使用 readline 解决此问题,或者您可以先将 typeglob 分配给标量(如您的示例所示)。