0

I would like to write a subroutine (say s2r) which can convert SCALAR input, which is a valid stringified reference, to REF type. As a bonus, I'd like the subroutine to convert the input to the original blessed object (or tied reference), if the input were the corresponding stringified version. My plan is to use this subroutine as a debugging utility (e.g. to see what references may have been accidentally stored as hash keys).

My initial prototype (which failed) was something like this:

#!/usr/bin/env perl

use strict;
use warnings;

use Scalar::Util qw(reftype);

sub bad_s2r {
    my $thing = shift or return undef;
    return eval {
        no strict 'refs';
        $thing =~ /^HASH\b/ ? \%$thing : $thing =~ /^ARRAY\b/ ? \@$thing : \$$thing
    };
}

my $ref = [];
my $str = "$ref";

print $ref, "\n";
print bad_s2r($str), "\n";

I was getting this output:

ARRAY(0x7fde1a0070d0)
ARRAY(0x7fde1a007310)

I highly suspect I was taking the reference of a duplicate of the original array.

Is there any way to treat the scalar as a reference, perhaps using the Perl Compiler Backend B or another module, or perhaps walking through all possible references that exist in the program and comparing the input against their stringified values? I don't mind if it's inefficient, just as long as it's possible.

If it's not possible to do something like this, is there any reason why it wouldn't be so?

Moh
  • 304
  • 2
  • 8

0 Answers0