\*DATA和*DATA之间的区别

Mil*_*ler 7 perl

每当我想模拟输入和输出到文件句柄时,我通常会分别使用引用DATASTDOUT:

use strict;
use warnings;
use autodie;

#open my $infh, '<', 'infile.txt';
my $infh = \*DATA;

#open my $outfh, '>', 'outfile.txt';
my $outfh, \*STDOUT;

print $outfh <$infh>;

__DATA__
Hello World
Run Code Online (Sandbox Code Playgroud)

输出:

Hello World
Run Code Online (Sandbox Code Playgroud)

然而,在鲍罗丁最近的回答中,证明实际上没有必要参考.相反,简单的分配就足够了:

my $infh = *DATA;
Run Code Online (Sandbox Code Playgroud)

因此,我创建了以下脚本来比较和对比这两种方法之间的区别:

use strict;
use warnings;

use Fcntl qw(:seek);

# Compare Indirect Filehandle Notation
my %hash = (
    '\*DATA' => \*DATA,
    '*DATA'  => *DATA,
);

my $pos = tell DATA;

my $fmt = "%-8s %-22s %-7s %s\n";
printf $fmt, qw(Name Value ref() readline());

while ( my ( $name, $fh ) = each %hash ) {
    seek( $fh, $pos, SEEK_SET );    # Rewind FH
    chomp( my $line = <$fh> );
    printf $fmt, $name, $fh, ref($fh), $line;
}

__DATA__
Hello World
Run Code Online (Sandbox Code Playgroud)

输出:

Name     Value                  ref()   readline()
\*DATA   GLOB(0x7fdc43027e70)   GLOB    Hello World
*DATA    *main::DATA                    Hello World
Run Code Online (Sandbox Code Playgroud)

当涉及从文件句柄传递和读取时,typeglob和对typeglob的引用之间没有区别.

从测试切换到研究形式的调查揭示了以下perldoc页面:

第一个参考建议使用.虽然第二个也提供了其他备选方案的列表,但提到如果我们想要保佑变量,如何需要引用符号.没有其他建议.

这两个间接文件句柄是否存在功能或首选风格差异?

  1. my $fh = \*DATA;
  2. my $fh = *DATA;

ike*_*ami 9

一个是水珠; 一个是对glob的引用.大多数地方同时接受.许多人还接受glob的名称作为字符串,并且许多人接受对IO对象的引用.

# Symbolic reference to the glob that contains the IO object.
>perl -E"$fh = 'STDOUT';    say $fh 'hi'"
hi

# Reference to the glob that contains the IO object.
>perl -E"$fh = \*STDOUT;    say $fh 'hi'"
hi

# Glob that contains the IO object.
>perl -E"$fh = *STDOUT;     say $fh 'hi'"
hi

# Reference to the IO object.
>perl -E"$fh = *STDOUT{IO}; say $fh 'hi'"
hi
Run Code Online (Sandbox Code Playgroud)

open(my $fh, '<', ...)填充$fh了一个对glob的引用,它是最受支持的,所以这就是我必须选择的东西.