如何在 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”实际写入由文件句柄指示的文件,假设文件句柄是成功“写入”打开的结果。
但是,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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将
$self->{_fd}
表达式放入块中或将其分配给更简单的表达式:来自
perldoc -f print
:You will need to put the
$self->{_fd}
expression in a block or assign it to a simpler expression:From
perldoc -f print
:交替:
Alternately: