且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Perl中将数组引用的字符串化版本转换为实际的数组引用?

更新时间:2023-11-07 15:40:46

是的,您可以执行此操作(即使没有Inline C).一个例子:

Yes, you can do this (even without Inline C). An example:

use strict;
use warnings;

# make a stringified reference
my $array_ref = [ qw/foo bar baz/ ];
my $stringified_ref = "$array_ref";

use B; # core module providing introspection facilities
# extract the hex address
my ($addr) = $stringified_ref =~ /.*(0x\w+)/;
# fake up a B object of the correct class for this type of reference
# and convert it back to a real reference
my $real_ref = bless(\(0+hex $addr), "B::AV")->object_2svref;

print join(",", @$real_ref), "\n";

但是不要那样做.如果您的实际对象已释放或重用,则可能会 最终出现段错误.

but don't do that. If your actual object is freed or reused, you may very well end up getting segfaults.

无论您实际上要实现什么目标,肯定都有更好的方法. 对另一个答案的评论表明,字符串化是由于使用引用作为哈希键所致.正如对此的回应,更好的方法是经过充分的考验 Tie :: RefHash .

Whatever you are actually trying to achieve, there is certainly a better way. A comment to another answer reveals that the stringification is due to using a reference as a hash key. As responded to there, the better way to do that is the well-battle-tested Tie::RefHash.