【问题标题】:How do I get access to filehandle and format respectively by typeglob?如何通过 typeglob 分别访问文件句柄和格式?
【发布时间】:2011-07-21 13:41:14
【问题描述】:

似乎filehandleformat 没有任何前缀,所以我无法通过%{*spud} 之类的技巧来引用它们。

我有什么遗漏的吗?

更新

如何访问format?为什么$fd=*STDOUT$fd=\*STDOUT 都有效?

更新2

代码:

package Foo;
our $spud = 'a scalar';
our @spud = 'an array';
our %spud = (a => 'hash');
sub spud {}
format spud =
.
open 'spud', $0; 

my $stash = \%Foo::;
my $name  = 'spud';
my $glob  = $$stash{$name};

for my $type (qw(SCALAR ARRAY HASH CODE IO FORMAT)) {
    #this works
    #print *$glob{$type}, $/; 
    #this doesn't work,only output one row of scalar                                  
    print *{$FOO::{spud}}{$type}, $/; 
}

输出:

[root@perl]# perl tb
SCALAR(0xa4dcf30)





[root@perl]# 

【问题讨论】:

    标签: perl typeglob


    【解决方案1】:
    {package Foo;
        our $spud = 'a scalar';
        our @spud = 'an array';
        our %spud = (a => 'hash');
        sub spud {}
        format spud =
    .
        open 'spud', $0;
    }
    
    my $stash = \%Foo::;
    my $name  = 'spud';
    my $glob  = $$stash{$name};
    
    for my $type (qw(SCALAR ARRAY HASH CODE IO FORMAT)) {
         print *$glob{$type}, $/;
    }
    

    打印:

    标量(0x810070) 数组(0x81c750) 哈希(0x81bb00) 代码(0x81bbd0) IO::句柄=IO(0x81b670) 格式(0x81bc40)

    【讨论】:

    • 所以FORMAT只能通过hash key而不是一些前缀来访问?
    • 我不太明白*$glob{$type} 在这里的工作原理...您能详细说明一下吗?
    • @R__ => 您可以将 glob 视为仅具有与 Perl 核心数据类型对应的键的受限哈希。因此,如果$typeARRAY,那么*$glob{$type} 将返回对存储在glob 中的ARRAY 的引用(在本例中为@Foo::spud)。您当然可以在没有所有变量间接的情况下执行此操作:*{$Foo::{spud}}{ARRAY}
    • @R__ => 是的,FORMATIO 类型没有自己的印记,因此要直接访问它们,您需要访问它们在 glob 中的插槽。
    • 您提到 perl 会自动取消引用用作文件句柄的 typeglob,如果是这样,为什么 \\*STDOUT 不起作用?我认为它应该通过取消引用两次来工作。
    【解决方案2】:

    *spud 将为您提供 glob 类型的文件句柄。见这里:Typeglobs and Filehandles

    【讨论】:

    • 另外,我不明白为什么$fh = *STDOUT;$fh = \*STDOUT; 相同...某事和对某事的引用应该不同,对吧?
    • @R__ => 当使用文件句柄时,Perl 通常不关心你是否给它一个 glob 或一个 glob 的引用,它会自动做正确的事情。这是 Perl 会自动取消引用某些内容的唯一一次。
    • @R__, *STDOUT (a glob) 与 \*STDOUT (a ref to a glob) 不同。许多内置函数都接受两者。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    相关资源
    最近更新 更多