为什么我的 Perl 祝福文件句柄不使用“can('print')”返回 true?
由于某种原因,我无法使用 Expect.pm 的 log_file
方法获取文件句柄。我最初获得了有关 如何将文件句柄传递给 Perl Expect 的 log_file 函数的帮助?,其中建议我使用 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。我这里错了吗?
For some reason, I can't get filehandles working with Expect.pm's log_file
method. I originally got help on How can I pass a filehandle to Perl Expect's log_file function?, where it was suggested that I use an IO::Handle filehandle to pass to the method. This seems to be a different issue, so I thought I'd start a new question.
This is the offending section of 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'. To my mind, the $fh->can
line should return true. Am I wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
奇怪的是,看起来您需要创建一个真正的
IO::File
对象以使can
方法起作用。尝试Odd, it looks like you need to create a real
IO::File
object to get thecan
method to work. TryIO::Handle
不会重载open()
函数,因此您实际上并没有在IO::Handle
中获取IO::Handle
对象代码>$fh。我不知道为什么$fh->print("Hello, world")
行有效(可能是因为您正在调用print()
函数,并且当您执行诸如$foo->function
之类的操作时,它相当于function $foo
,因此您实际上是像通常期望的那样打印到文件句柄)。如果您将代码更改为以下内容:
...那么您的代码将按照您的预期运行。至少,对我来说是这样!
IO::Handle
doesn't overload theopen()
function, so you're not actually getting anIO::Handle
object in$fh
. I don't know why the$fh->print("Hello, world")
line works (probably because you're calling theprint()
function, and when you do things like$foo->function
it's equivalent tofunction $foo
, so you're essentially printing to the filehandle like you'd normally expect).If you change your code to something like:
...then your code will do as you expect. At least, it does for me!