如何在 Perl 类中存储和访问文件句柄? [英] How can I store and access a filehandle in a Perl class?

查看:61
本文介绍了如何在 Perl 类中存储和访问文件句柄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请先看下面的代码.

#! /usr/bin/perl
package foo;

sub new {

    my $pkg = shift;
    my $self = {};
    my $self->{_fd} = undef;
    bless $self, $pkg;

    return $self;
}

sub Setfd {

    my $self = shift;
    my $fd = shift;
    $self_->{_fd} = $fd;
}

sub write {

    my $self = shift;
    print $self->{_fd} "hello word";
}

my $foo = new foo;

我的目的是使用哈希在类中存储文件句柄.文件句柄一开始是未定义的,但可以通过调用 Setfd 函数在之后初始化.然后可以调用 write 将字符串hello word"实际写入文件句柄指示的文件中,假设文件句柄是写"打开成功的结果.

My intention is to store a file handle within a class using hash. the file handle is undefined at first, but can be initilized afterwards by calling Setfd function. then write can be called to actually write string "hello word" to a file indicated by the file handle, supposed that the file handle is the result of a success "write" open.

但是,perl 编译器只是抱怨print"行中有语法错误.你们中的任何人都可以告诉我这里有什么问题吗?提前致谢.

but, perl compiler just complains that there are syntax error in the "print" line. can anyone of you tells me what's wrong here? thanks in advance.

推荐答案

您需要将 $self->{_fd} 表达式放在块中或将其分配给更简单的表达式:

You will need to put the $self->{_fd} expression in a block or assign it to a simpler expression:

    print { $self->{_fd} } "hello word";

    my $fd = $self->{_fd};
    print $fd "hello word";

来自perldoc -f print:

请注意,如果您将 FILEHANDLE 存储在数组中,或者如果您使用比标量变量更复杂的任何其他表达式来检索它,则必须使用返回文件句柄值的块:

Note that if you're storing FILEHANDLEs in an array, or if you're using any other expression more complex than a scalar variable to retrieve it, you will have to use a block returning the filehandle value instead:

print { $files[$i] } "stuff\n";
print { $OK ? STDOUT : STDERR } "stuff\n";

这篇关于如何在 Perl 类中存储和访问文件句柄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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