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

查看:21
本文介绍了如何将字符串化版本的数组引用转换为 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.

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

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