【问题标题】:How can I make a Perl variable reference another variable by its integer reference如何通过整数引用使 Perl 变量引用另一个变量
【发布时间】:2011-03-28 04:06:34
【问题描述】:

我相信我的标题可能有点令人困惑,但这里是我想要做的事情的要点。我知道这不是“正确的方法”,我只是好奇它是否可能。

假设我有脚本:

#!/usr/bin/perl

use strict;
use warnings;

my $foo = "bar";
my $foo_location = int(\$foo);

print $foo_location;

此输出将类似于 136167064

如何获取该整数($foo 在内存中的位置),并使用该整数创建另一个引用 $foo 的变量。

所以我想做的是:

my $foo_reference = some_magical_function_call($foo_location);

这将允许修改 $foo_reference 的取消引用,以修改 $foo 的值。所以在任何魔法允许它起作用之后,

$$foo_reference eq $foo

评估结果为真

我想说我几年前就知道了,但也许我疯了。

【问题讨论】:

  • 这纯粹是学术性的,还是您有一些用例?

标签: perl memory integer reference


【解决方案1】:

啊,哎呀。我找到了答案。我可能应该在发布之前等待。

无论如何,如果有人好奇:

#!/usr/bin/perl
use strict;
use warnings;
use B;


my $foo = "bar";
my $foo_location = int(\$foo);

my $real_ref = bless(\(0+hex sprintf("%0x",$foo_location)), "B::AV")->object_2svref;

print $$real_ref;

打印条

我从this question的回答中发现了这一点

【讨论】:

  • 你可以只做bless(\$foo_location, "B::AV")->object_2svref,因为你已经有了 int 值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-08
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多