[英]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::FILE
从FILE
句柄中读取内容,如下所示
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: 这有两个优点:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.