gpt4 book ai didi

perl - 为什么在逐行读取时 ${fh} 的行为与 $fh 不同?

转载 作者:行者123 更新时间:2023-12-04 02:40:32 24 4
gpt4 key购买 nike

这个脚本:

#!/usr/bin/perl
use strict;
use warnings;

my ${fh};

open($fh, '<', "some_file.txt") or die "fail\n";

while(my $line = <${fh}> ) {
print $line;
}
close $fh;

输出:
GLOB(0x5bcc2a0)

为什么是这个输出?

如果我改变 <${fh}><$fh> ,它会打印 some_file.txt按预期逐行。我认为大括号可以用来分隔变量名,而 my ${var}将与 my $var 相同.

是否还有其他场景添加 {}围绕变量名会导致问题吗?

我在 Red Hat 和 Cygwin Perl 5.14 上尝试了 Perl 5.8.8。

最佳答案

来自 <> 的部分在 perlop :

If what the angle brackets contain is a simple scalar variable (for example, $foo), then that variable contains the name of the filehandle to input from, or its typeglob, or a reference to the same. For example:

$fh = \*STDIN;
$line = <$fh>;

If what's within the angle brackets is neither a filehandle nor a simple scalar variable containing a filehandle name, typeglob, or typeglob reference, it is interpreted as a filename pattern to be globbed, and either a list of filenames or the next filename in the list is returned, depending on context. This distinction is determined on syntactic grounds alone. That means <$x> is always a readline() from an indirect handle, but <$hash{key}> is always a glob(). That's because $x is a simple scalar variable, but $hash{key} is not--it's a hash element. Even <$x > (note the extra space) is treated as glob("$x "), not readline($x).



你可以用 B::Concise 看到这个:

$ perl -MO=Concise -e'<$fh>'
5 <@> leave[1 ref] vKP/REFC ->(end)
1 <0> enter ->2
2 <;> nextstate(main 1 -e:1) v:{ ->3
4 <1> readline[t1] vK*/1 ->5
- <1> ex-rv2sv sK/1 ->4
3 <$> gvsv(*fh) s ->4
-e syntax OK

$ perl -MO=Concise -e'<${fh}>'
6 <@> leave[1 ref] vKP/REFC ->(end)
1 <0> enter ->2
2 <;> nextstate(main 70 -e:1) v:{ ->3
5 <@> glob[t1] vK/1 ->6
- <0> ex-pushmark s ->3
- <1> ex-rv2sv sK/1 ->4
3 <$> gvsv(*fh) s ->4
4 <$> gv(*_GEN_0) s ->5
-e syntax OK

关于perl - 为什么在逐行读取时 ${fh} 的行为与 $fh 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34821209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com