如何在Perl中将数组引用的字符串化版本转换为实际的数组引用? [英] How can I convert the stringified version of array reference to actual array reference in Perl?

查看:96
本文介绍了如何在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
    ];

推荐答案

是的,您可以执行此操作(即使没有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.

这篇关于如何在Perl中将数组引用的字符串化版本转换为实际的数组引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆