简体   繁体   English

在Perl中,bareword filehandle包变量是否可变?

[英]Is bareword filehandle package variable in Perl?

The legacy bareword filehandle looks in global scope, is it parsed as package variable? 旧的裸字文件句柄在全局范围内查找,是否将其解析为包变量? Why isn't it prepended with punctuation sign ( $ )? 为什么不加标点符号( $ )?

open FILE, 'file.txt';

If you look at perldoc -f ref you will see that there are more data types than there are identifying sigils. 如果查看perldoc -f ref ,将会看到数据类型多于标识信号。 The only defined ones are 唯一定义的是

  • $ - SCALAR $ - 标量
  • @ - ARRAY @ - 阵列
  • % - HASH % - 哈希
  • & - CODE & - 代码

the rest are identified by context. 其余的由上下文标识。

If you write 如果你写

package Pack;

open FH, '<', 'file';

then FH appears in the Pack symbol table as the IO variable Pack::FH . 然后FH作为IO变量Pack::FH出现在Pack符号表中。 It isn't preceded by a dollar $ because it is an IO variable, not a SCALAR . 它前面没有美元$因为它是IO变量,而不是SCALAR Without a preceding package statement, it will be placed in the default main namespace. 如果没有前面的package语句,它将被放置在默认的main命名空间中。 So with your example 所以以你的例子

open FILE, 'file.txt'

you can then read from the FILE handle using the fully-qualified main::FILE like this 然后您可以使用完全合格的main::FILEFILE句柄中读取内容,如下所示

while (<main::FILE>) {
  :
  :
}

Used to be a convention in Perl - filehandles were all uppercase, and globally scoped. 过去在Perl中是一个约定-文件句柄全部为大写且在全局范围内。

This started with STDIN (and the other standard file streams) and so you could do: 这从STDIN (和其他标准文件流)开始,因此您可以执行以下操作:

while ( <STDIN> ) {
    print;
}

Perl's open command supports a 'legacy' mode of opening, which is: Perl的open命令支持“旧式”打开模式,即:

open ( FILEHANDLE, ">filename.txt" );

It's not recommended to use this any more, but it can't be removed without breaking legacy code. 不建议再使用它,但是在不破坏旧代码的情况下将其删除。

Instead you should: 相反,您应该:

 open ( my $filehandle, ">", 'filename.txt' ) or die $!;
 print {$filehandle} "Some Text\n";

This has two advantages: 这有两个优点:

  • your filehandle is lexically scoped, so you don't have to worry about a module writing to 'OUTPUT' or similar. 您的文件句柄具有词法范围,因此您不必担心模块会写入“ OUTPUT”或类似内容。
  • Because it's lexically scoped, it automatically closes when it goes out of scope. 因为它是词法范围的,所以超出范围时它将自动关闭。
  • 3 argument open avoids injection exploits. 3论点开放避免了注入漏洞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM