确定标量是否包含文件句柄的最佳方法是什么? [英] What is the best way to determine if a scalar holds a filehandle?

查看:53
本文介绍了确定标量是否包含文件句柄的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定给定的标量是否包含文件句柄.它可以从一个裸字文件句柄(即 \*FH)、一个词法文件句柄、一个 IO::Handle、一个 IO::File 等传递给我.到目前为止,唯一的似乎在各种风格中一致的是它们都有一个 reftype<"GLOB" 的/code>.

I am trying to determine if a given scalar holds a filehandle. It could have been passed to me from a bareword filehandle (i.e. \*FH), a lexical filehandle, an IO::Handle, an IO::File, etc. So far, the only thing that seems to be consistent amongst the various flavors is that they all have a reftype of "GLOB".

推荐答案

使用 openhandle 函数来自 Scalar::Util:

openhandle FH

如果 FH 可以用作文件句柄并且是打开的,或者 FH 是一个绑把手.否则 undef 是返回.

Returns FH if FH may be used as a filehandle and is open, or FH is a tied handle. Otherwise undef is returned.

  $fh = openhandle(*STDIN);           # \*STDIN
  $fh = openhandle(\*STDIN);          # \*STDIN
  $fh = openhandle(*NOTOPEN);         # undef
  $fh = openhandle("scalar");         # undef

当前的实现类似于 Greg Bacon 的回答,但它有一些额外的测试.

The current implementation is similar to Greg Bacon's answer, but it has some additional tests.

这篇关于确定标量是否包含文件句柄的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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