“$ var = * $ self-> {class_var};”是什么意思

时间:2011-02-11 15:11:24

标签: perl

我试图搜索这个,但没有提出任何建议。

我很好奇为什么会把星号放在下面的场景中:

$var = *$self->{class_var};

*在这种情况下做了什么?

更新

我从Net :: Telnet模块中取得了上述内容,我只是想了解它。

实际代码是:

$s = *$self->{net_telnet};

我想知道,net_telnet是包名吗?

5 个答案:

答案 0 :(得分:8)

%main::some_hash = (class_var => 'xyz');

my $self = *main::some_hash;

print *$self->{class_var}, "\n";   # prints 'xyz'

简而言之,这是一种过时的方式来传递对符号表中哈希的引用。 *之前的$self取消引用$self中的值作为typeglob。 ->{class_var}然后将typeglob取消引用为哈希,并查找class_var密钥。

更新

向下挖掘类层次结构,可以发现该对象是在IO::Handle中使用:

创建的
sub new {
    my $class = ref($_[0]) || $_[0] || "IO::Handle";
    @_ == 1 or croak "usage: new $class";
    my $io = gensym;
    bless $io, $class;
}

Symbol::gensym返回一个完整的typeglob,主要使用IO个插槽。但是,由于它是一个完整的typeglob,子模块正在利用这一事实并将其数据存储在各种其他glob字段中,即HASH部分。

答案 1 :(得分:6)

从我的短代码中我假设$self拥有一个typeglob。您可以像eugene提到的那样显式地访问子元素,或者通过在typeglob上使用任何标准的解引用语法来隐式访问。

#!/usr/bin/perl

use strict;
use warnings;

our %test = ( class_var => "test class_var" );
our @test = qw(one four nine);

my $self = \*test;
print "Self is '$self'\n";

my $var1 = *{$self}{HASH}{class_var};
print "Var1 is '$var1'\n";

my $var2 = *$self->{class_var};
print "Var2 is '$var2'\n";

my $var3 = ${*{$self}}{class_var};
print "Var3 is '$var3'\n";

my $var4 = ${*$self}{class_var};
print "Var4 is '$var4'\n";

my $x_scale = *$self{ARRAY}[0];
print "x_scale is '$x_scale'\n";

my $y_scale = *$self->[1];
print "y_scale is '$y_scale'\n";

my $z_scale = ${*$self}[2];
print "z_scale is '$z_scale'\n";

Typeglob引用(符号别名之外)最常用于IO槽,它允许将对象用作文件句柄,但由于typeglob包含每种类型的变量之一,因此其他变量槽可用于存储其他状态数据。

typeglob不一定是全局的,Symbol::gensym可以创建一个基本上是匿名的typeglob。

答案 2 :(得分:3)

这很可能是处理文件句柄对象。文件句柄本身存储在glob的fh槽中,但有关文件句柄的元数据存储在glob的哈希槽中。

所以这就是说

$var = *{$self}{class_var}

即。取消引用$ self作为typeglob,然后将其用作哈希。

你不能做$ self-> {class_var}因为它不是HASH引用,它是一个GLOB引用。

use strict;

my $fh;    

my $self = \*fh;

*$self->{val} = 'foo';

我使用$fh作为示例,但事实上IO :: Handle(可能)将使用其他方式创建glob ref。但是使用这段代码你应该看到

print ref $self;

GLOB,但你仍然可以

print *$self->{val};

获取foo

进一步阅读:http://perldoc.perl.org/perldata.html#Typeglobs-and-Filehandles

答案 3 :(得分:3)

*$var语法允许您按名称访问一组全局变量。例如,$foo@foo%foo*foo

package main;
no strict;
$foo = 'bar';     # global variable!
@main::foo = qw(an array);
%foo = ('hash' => 'table');
open foo, '>', '/tmp/foo';

$self = 'foo';

print "\$$self is ${*$self}\n";   # $foo
print "\@$self is @{*$self}\n";   # @foo 
print "\%$self is {",
  (map {$_, " => ", *$self->{$_}, ","} keys %{*$self}),
  "}\n";
print "Performing operations on the $self filehandle:\n";
print {*$self} "hello world\n";
close *$self;

open X, '<', '/tmp/foo'; 
print <X>; 
close X;

$foo is bar
@foo is an array
%foo is {hash => table,}
Performing operations on the foo filehandle:
hello world

当然,在这些带有引用和词汇变量的现代,用这样的代码完成的任何事情都可能以更好的方式完成。

答案 4 :(得分:2)

看起来像某人用typeglobs做某事;例如* $ self可以是实现文件句柄的子类
@Dave Sherohman,看看IO::Pipe的来源。它包含一些有趣的代码,它们可以在类型问题中播放很多类型

相关问题