perl - ref($variable) 什么时候返回 'IO' ?

标签 perl filehandle

这是 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/

相关文章:

python - 读取整个文件是否会使文件句柄保持打开状态?

database - Bucardo 添加同步以复制数据

regex - 如何重建正则表达式匹配部分

perl - 在 Perl 中,如何区分 JSON 编码中的数字和字符串哈希值?

Perl glob 和文件句柄问题

perl - 如何检查Perl中是否打开了文件句柄?

linux - Perl - 在 Linux 上获取可用磁盘空间使用情况

perl - 如何根据一组行的列的最低值对文本文件的内容进行排序

java - 如何在通过 JGit 克隆 repo 后释放文件系统锁

c++ - 获取不带扩展名的文件名?