ref($variable) 什么时候返回 'IO'? [英] When does ref($variable) return 'IO'?

查看:51
本文介绍了ref($variable) 什么时候返回 'IO'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是 ref 文档的相关摘录a> 功能:

Here's the relevant excerpt from the documentation of the ref function:

返回的值取决于引用所引用的事物的类型.内置类型包括:

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'.令人惊讶的是,它没有:


Based on this, I imagined that calling ref on a filehandle would return 'IO'. Surprisingly, it doesn't:

use strict;
use warnings;

open my $fileHandle, '<', 'aValidFile';
close $fileHandle;

print ref $fileHandle;     # prints 'GLOB', not 'IO'

<小时>

perlref 试图解释原因:


perlref tries to explain why:

不可能创建一个真正的对 IO 句柄的引用(文件句柄或 dirhandle) 使用反斜杠操作员.你最多能得到一个对 typeglob 的引用,即实际上是一个完整的符号表进入 [...] 但是,您仍然可以使用类型 globs 和 globrefs好像它们是 IO 句柄.

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} 语法:

The only way to get an IO reference is to use the *FOO{THING} syntax:

$ioref = *glob{IO};

其中 glob 是像 STDIN 这样的命名 glob 或像 $fh 这样的引用.但是一旦你有了这样一个引用,它可以像任何其他标量一样被传递或存储在任意数据结构中,所以像编组模块这样的事情需要精通它.

where glob is a named glob like STDIN or a reference like $fh. But once you have such a reference, it can be passed around or stored in arbitrary data structures just like any other scalar, so things like marshalling modules need to be savvy of it.

由于 glob 或 globref 可以用作文件句柄并隐式获取包含的 IO 事物,因此不需要很多 IO 引用.主要的例外是:

Since a glob or globref can be used as a filehandle and implicitly get the contained IO thingy, there isn't a lot of need for IO refs. The main exception is this:

use Symbol;
# replace *FOO{IO} handle but not $FOO, %FOO, etc.
*FOO = geniosym;

(geniosym 返回一个新的半匿名 IO 引用,任何非 glob 引用到 glob 的赋值只分配给该特定引用的 glob 部分)

(geniosym returns a new semi-anonymous IO reference, and any non-glob reference-to-glob assignment only assigns to that particular reference's part of the glob)

这篇关于ref($variable) 什么时候返回 'IO'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆