这是 ref
文档的相关摘录功能:
The value returned depends on the type of thing the reference is a reference to. Builtin types include:
SCALAR ARRAY HASH CODE REF GLOB LVALUE FORMAT IO VSTRING Regexp
基于此,我想象调用
ref
在文件句柄上将返回 'IO'
.令人惊讶的是,它没有:use strict;
use warnings;
open my $fileHandle, '<', 'aValidFile';
close $fileHandle;
print ref $fileHandle; # prints 'GLOB', not 'IO'
perlref
试图解释原因:It isn't possible to create a true reference to an IO handle (filehandle or dirhandle) using the backslash operator. The most you can get is a reference to a typeglob, which is actually a complete symbol table entry [...] However, you can still use type globs and globrefs as though they were IO handles.
在什么情况下
ref
返回 'IO'
然后?
最佳答案
获取 IO 引用的唯一方法是使用 *FOO{THING} 语法:
$ioref = *glob{IO};
其中 glob 是像 STDIN 这样的命名 glob 或像 $fh 这样的引用。但是一旦你有了
这样一个引用,它可以像任何其他标量一样被传递或存储在任意数据结构中,所以像编码模块这样的东西需要精通它。
由于 glob 或 globref 可以用作文件句柄并隐式获取包含的 IO 事物,因此对 IO refs 的需求并不多。主要的异常(exception)是:
use Symbol;
# replace *FOO{IO} handle but not $FOO, %FOO, etc.
*FOO = geniosym;
(geniosym 返回一个新的半匿名 IO 引用,并且任何非 glob 引用到 glob 分配仅分配给该特定引用的 glob 部分)
关于perl - ref($variable) 什么时候返回 'IO' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2955428/