由于某些原因,我无法使用expect.pm的log_file方法获得文件句柄。我最初得到了有关How can I pass a filehandle to Perl Expect's log_file function?的帮助,其中有人建议我使用IO::Handle文件句柄来传递给该方法。这似乎是一个不同的问题,所以我想我应该开始一个新的问题。
这是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
}因此,我尝试了以下示例代码:
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";
}当我运行这个的时候,我得到了两个(在我看来)相互冲突的项目。一个只有一行的文件,显示'Hello,world',输出为'No‘。在我看来,$fh->can行应该返回true。我说错了吗?
发布于 2010-09-16 03:46:52
奇怪的是,看起来您需要创建一个真正的IO::File对象才能使can方法工作。试一试
use IO::File;
my $fh = IO::File->new("file.out", ">>")
or die "Couldn't open file: $!";发布于 2010-09-16 03:45:06
IO::Handle不会重载open()函数,因此您实际上不会在$fh中获得IO::Handle对象。我不知道为什么$fh->print("Hello, world")行可以工作(可能是因为您调用的是print()函数,而当您执行诸如$foo->function之类的操作时,它等同于function $foo,因此您实际上是像通常所期望的那样打印到文件句柄)。
如果您将代码更改为类似以下内容:
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你的代码将会如你所愿。至少对我来说是这样的!
https://stackoverflow.com/questions/3721148
复制相似问题