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

前端之家收集整理的这篇文章主要介绍了如何将字符串化版本的数组引用转换为Perl中的实际数组引用?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法让Perl将数组引用的字符串化版本(例如ARRAY(0x8152c28))转换为实际的数组引用?

例如

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

会屈服

$VAR1 = [
      1,3
    ];

解决方法

是的,你可以这样做(即使没有内联C).一个例子:

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";

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

无论你实际想要实现什么,肯定有更好的方法.
对另一个答案的评论表明,字符串化是由于使用引用作为哈希键.作为回应,更好的方法是经过良好的战斗测试
Tie::RefHash.

猜你在找的Perl相关文章