perl - 如何在 Perl 中使用类属性/变量作为打印文件句柄?

标签 perl class syntax file-writing

我想做同样的事情

open MYFILE, ">", "data.txt";
print MYFILE "Bob\n";

而是在类变量中
sub _init_tmp_db
{
    my ($self) = @_;

    open $$self{tmp_db_fh}, ">", "data.txt";
    print $$self{tmp_db_fh} "Bob\n";
}

它给了我这个错误:'在“Bob\n”附近找到运算符(operator)预期的字符串'

我该怎么办?

最佳答案

来自 print manpage :

If you're storing handles in an array or hash, or in general whenever you're using any expression more complex than a bareword handle or a plain, unsubscripted scalar variable to retrieve it, you will have to use a block returning the filehandle value instead.



你应该使用:
print { $$self{tmp_db_fh} } "Bob\n";

此代码在 use strict 下不起作用.要修复它,只需使用 my多变的:
open my $fh, ">", "data.txt" or die $!;
$$self{tmp_db_fh} = $fh;
print { $$self{tmp_db_fh} } "Bob\n";

关于perl - 如何在 Perl 中使用类属性/变量作为打印文件句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9065143/

相关文章:

javascript - 解释ES6类构造函数和箭头函数的作用

php 语法 $a = $b = 1;

javascript - 正则表达式搞乱了语法突出显示

syntax - 如何从 SyntaxNet 获取依存分析输出

arrays - 在Perl中,@ array [1]和$ array [1]有什么区别?

linux - 如何使用带有 Perl -e 参数的 cat 读取文件?

Perl:无法通过包定位对象方法栏

php - 在 PHP 中调用另一个类中的一个类

C++ 不能创建抽象类的实例

arrays - 在 Perl 中让数组元素以特定关键字结尾并将其余元素移至下一行