$ref = \%hash;
$ref = \@hash;
我如何使用 做与引用相同的事情typeglob 在 perl 中?
perl 解释的确切步骤是什么
$$ref{key}
?
最佳答案
使用 *foo{THING}
语法,记录在 Making References section 中的 perlref 文档。
A reference can be created by using a special syntax, lovingly known as the
*foo{THING}
syntax.*foo{THING}
returns a reference to the THING slot in*foo
(which is the symbol table entry which holds everything known asfoo
).$scalarref = *foo{SCALAR}; $arrayref = *ARGV{ARRAY}; $hashref = *ENV{HASH}; $coderef = *handler{CODE}; $ioref = *STDIN{IO}; $globref = *foo{GLOB}; $formatref = *foo{FORMAT};
例如:
#! /usr/bin/env perl
use strict;
use warnings;
our %hash = (Ralph => "Kramden", Ed => "Norton");
our @hash = qw/ apple orange banana cherry kiwi /;
my $ref;
$ref = *hash{HASH};
print $ref->{Ed}, "\n";
$ref = *hash{ARRAY};
print $ref->[1], "\n";
输出:
Norton orange
As for the second part of your question, adding
print $$ref{Ralph}, "\n";
在 Ed 产生预期输出之后。编译器为这一行生成代码,其顺序如下:
$ref
的焊盘条目. $ref
的东西。 但不要相信我的话。要减少输出量,请考虑类似的两行:
my $ref = { Ralph => "Kramden" };
print $$ref{Ralph};
使用为调试而编译的 perl 运行它会得到我们
$ debugperl -Dtls ref
[...]
(ref:1) nextstate
=>
(ref:2) pushmark
=> *
(ref:2) padsv($ref) # 第 1 步
=> *\HV()
(ref:2) rv2hv # 第 2 步
=> * HV()
(ref:2) const(PV("Ralph"\0)) # STEP 3a
=> * HV() PV("拉尔夫"\0)
(ref:2) helem # 第 3b 步
=> * PV("克拉姆登"\0)
(ref:2) 打印
=> SV_YES
(ref:2) 离开
[...]
请注意,全局变量略有不同。
我不确定您的更大意图是什么,但有一些重要的警告。请注意,typeglob 表示一个符号表条目,因此您无法通过这种方式获得词法,因为它们位于填充中,而不是符号表中。例如,假设您插入
my @hash = ("splat");
就在分配给 $ref
之前在上面的代码中。结果可能会让你大吃一惊。$ ./程序
“我的”变量@hash 在 ./prog 第 11 行屏蔽了相同范围内的早期声明。
诺顿
橘子
关于标量的行为也可能令人惊讶。
*foo{THING}
returnsundef
if that particular THING hasn't been used yet, except in the case of scalars.*foo{SCALAR}
returns a reference to an anonymous scalar if$foo
hasn't been used yet. This might change in a future release.
告诉我们您正在尝试做什么,我们将能够为您提供具体、有用的建议。
关于perl - 如何在 perl 中使用 typeglob 做与引用相同的事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6505654/