How can I convert the stringified version of array reference to actual array reference in Perl?

前端 未结 6 574
南笙
南笙 2020-11-29 11:11

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?

For example



        
6条回答
  •  心在旅途
    2020-11-29 11:53

    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.

    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.

提交回复
热议问题