\ * DATA和* DATA之间的区别

时间:2014-09-10 23:18:55

标签: 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

输出:

Hello World

然而,在鲍罗丁的recent answer中,证明了实际上并不需要参考。相反,简单的分配就足够了:

my $infh = *DATA;

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

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

输出:

Name     Value                  ref()   readline()
\*DATA   GLOB(0x7fdc43027e70)   GLOB    Hello World
*DATA    *main::DATA                    Hello World

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

从测试转向研究形式的调查揭示了以下perldoc页面:

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

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

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

1 个答案:

答案 0 :(得分: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

open(my $fh, '<', ...)使用对glob的引用填充$fh,并且它是最受支持的,所以如果我必须选择的话,这就是我使用的内容。

相关问题