[英]Why doesn't my Perl blessed filehandle doesn't return true with `can('print')`'?
For some reason, I can't get filehandles working with Expect.pm's log_file
method. 出于某种原因,我无法使用Expect.pm的log_file
方法处理文件句柄。 I originally got help on How can I pass a filehandle to Perl Expect's log_file function? 我最初得到了帮助如何将文件句柄传递给Perl Expect的log_file函数? , where it was suggested that I use an IO::Handle filehandle to pass to the method. ,建议我使用IO :: Handle文件句柄传递给方法。 This seems to be a different issue, so I thought I'd start a new question. 这似乎是一个不同的问题,所以我想我会开始一个新的问题。
This is the offending section of Expect.pm: 这是Expect.pm的违规部分:
if (ref($file) ne 'CODE') {
croak "Given logfile doesn't have a 'print' method"
if not $fh->can("print");
$fh->autoflush(1); # so logfile is up to date
}
So, then, I tried this sample code: 那么,我尝试了这个示例代码:
use IO::Handle;
open $fh, ">>", "file.out" or die "Can't open file";
$fh->print("Hello, world");
if ($fh->can("print"))
{
print "Yes\n";
}
else
{
print "No\n";
}
When I run this, I get two (to my mind) conflicting items. 当我运行这个时,我得到两个(在我看来)冲突的项目。 A file with a single line that says 'Hello, world', and output of 'No'. 一行显示“Hello,world”和“No”输出的文件。 To my mind, the $fh->can
line should return true. 在我看来, $fh->can
行应该返回true。 Am I wrong here? 我错了吗?
IO::Handle
doesn't overload the open()
function, so you're not actually getting an IO::Handle
object in $fh
. IO::Handle
不会重载open()
函数,所以你实际上并没有在$fh
获取IO::Handle
对象。 I don't know why the $fh->print("Hello, world")
line works (probably because you're calling the print()
function, and when you do things like $foo->function
it's equivalent to function $foo
, so you're essentially printing to the filehandle like you'd normally expect). 我不知道为什么$fh->print("Hello, world")
行有效(可能是因为你正在调用print()
函数,当你执行$foo->function
之类的操作时,它等同于function $foo
,所以你基本上就像你通常所期望的那样打印到文件句柄。
If you change your code to something like: 如果您将代码更改为:
use strict;
use IO::Handle;
open my $fh, ">>", "file.out" or die "Can't open file";
my $iofh = new IO::Handle;
$iofh->fdopen( $fh, "w" );
$iofh->print("Hello, world");
if ($iofh->can("print"))
{
print "Yes\n";
}
else
{
print "No\n";
}
...then your code will do as you expect. ...然后你的代码会像你期望的那样。 At least, it does for me! 至少,它对我有用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.