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

前端 未结 6 562
南笙
南笙 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:50

    I'm not sure why you want to do this, but if you really need it, ignore the answers that use the tricks to look into memory. They'll only cause you problems.

    Why do you want to do this? There's probably a better design. Where are you getting that stringified reference from.

    Let's say you need to do it for whatever reason. First, create a registry of objects where the hash key is the stringified form, and the value is a weakened reference:

     use Scalar::Util qw(weaken);
    
     my $array = [ ... ];
    
     $registry{ $array } = $array;
    
     weaken( $registry{ $array } ); # doesn't count toward ref count
    

    Now, when you have the stringified form, you just look it up in the hash, checking to see that it's still a reference:

     if( ref $registry{$string} ) { ... }
    

    You could also try Tie::RefHash and let it handle all of the details of this.

    There is a longer example of this in Intermediate Perl.

提交回复
热议问题