请先查看以下代码.
#! /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;
我的目的是使用hash在类中存储文件句柄.文件句柄最初是未定义的,但之后可以通过调用Setfd函数来启动.然后
可以调用write来实际将字符串“hello word”写入文件句柄指示的文件,假设文件句柄是成功“写入”打开的结果.
但是,perl编译器只是抱怨“print”行中存在语法错误.谁能告诉我这里有什么问题?提前致谢.
解决方法
您需要将$self-> {_ fd}表达式放在块中或将其分配给更简单的表达式:
print { $self->{_fd} } "hello word"; my $fd = $self->{_fd}; print $fd "hello word";
从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";