请先查看以下代码.
#! /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;
Run Code Online (Sandbox Code Playgroud)
我的目的是使用hash在类中存储文件句柄.文件句柄最初是未定义的,但之后可以通过调用Setfd函数来启动.然后可以调用write来实际将字符串"hello word"写入文件句柄指示的文件,假设文件句柄是成功"写入"打开的结果.
但是,perl编译器只是抱怨"print"行中存在语法错误.谁能告诉我这里有什么问题?提前致谢.
mob*_*mob 15
您需要将$self->{_fd}表达式放在块中或将其指定给更简单的表达式:
print { $self->{_fd} } "hello word";
my $fd = $self->{_fd};
print $fd "hello word";
Run Code Online (Sandbox Code Playgroud)
请注意,如果您将FILEHANDLE存储在数组中,或者如果您正在使用比标量变量更复杂的任何其他表达式来检索它,则必须使用返回文件句柄值的块:
print { $files[$i] } "stuff\n";
print { $OK ? STDOUT : STDERR } "stuff\n";
Run Code Online (Sandbox Code Playgroud)
交替:
use IO::Handle;
# ... later ...
$self->{_fd}->print('hello world');
Run Code Online (Sandbox Code Playgroud)