加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 21:52:43 所属栏目:大数据 来源:网络整理
导读:请先查看以下代码. #! /usr/bin/perlpackage 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;
请先查看以下代码.
#! /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] } "stuffn";
print { $OK ? STDOUT : STDERR } "stuffn";

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读