gpt4 book ai didi

perl -\*DATA 和 *DATA 之间的区别

转载 作者:行者123 更新时间:2023-12-04 11:23:50 26 4
gpt4 key购买 nike

每当我想模拟文件句柄的输入和输出时,我会经常使用对 DATA 的引用。和 STDOUT分别:

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 中Borodin 证明实际上没有必要引用。相反,一个简单的赋值就足够了:
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

在传递和读取文件句柄时,类型团和对类型团的引用之间似乎没有区别。

从测试切换到研究形式的调查显示以下 perldoc 页面:
  • perldata - Typeglobs and Filehandles
  • perlfaq5 - How can I use a filehandle indirectly?

  • 第一个引用建议使用任何一种。虽然第二个也给出了其他替代方案的列表,但提到了如果我们想要保佑变量,引用符号是如何需要的。不建议其他区别。

    这两个间接文件句柄是否存在功能或首选样式差异?
  • my $fh = \*DATA;
  • my $fh = *DATA;
  • 最佳答案

    一个是一个球体; one 是对 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, '<', ...)填充 $fh引用一个 glob,它是最受支持的,所以如果我必须选择,这就是我使用的。

    关于perl -\*DATA 和 *DATA 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25776612/

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