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

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

问题描述:

有什么方法可以让 Perl 将字符串化的版本,例如数组引用的 (ARRAY(0x8152c28)) 转换为实际的数组引用?

Is there any way to get Perl to convert the stringified version e.g (ARRAY(0x8152c28)) of an array reference to the actual array reference?

例如

perl -e 'use Data::Dumper; $a = [1,2,3];$b = $a; $a = $a.""; warn Dumper (Then some magic happens);'

会屈服

$VAR1 = [
      1,
      2,
      3
    ];

是的,您可以这样做(即使没有内联 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 =~ /.*(0xw+)/;
# 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), "
";

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

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.