如何在 Perl 类中存储和访问文件句柄?

发布于 2024-09-05 08:14:18 字数 571 浏览 1 评论 0原文

请先看下面的代码。

#! /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”实际写入由文件句柄指示的文件,假设文件句柄是成功“写入”打开的结果。

但是,perl 编译器只是抱怨“print”行中有语法错误。你们谁能告诉我这里出了什么问题吗?提前致谢。

please look at the following code first.

#! /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;

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

許願樹丅啲祈禱 2024-09-12 08:14:18

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

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

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

来自 perldoc -f print

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

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

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";

From perldoc -f print:

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";
玻璃人 2024-09-12 08:14:18

交替:

use IO::Handle;

# ... later ...

$self->{_fd}->print('hello world');

Alternately:

use IO::Handle;

# ... later ...

$self->{_fd}->print('hello world');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文