rodd has asked for the wisdom of the Perl Monks concerning the following question:

Monks,

While debugging some code that's printing "HASH(0x9999999)" to stdout, I'd like to be able to parse that out and convert it to a real Perl hash to be able to identify the hash's origin from looking at its contents.

I found I can peek into its data structure using the following:

my ( $addr ) = 'HASH(0x9999999)' =~ /HASH\(0x(.*)\)/; $addr = hex $addr; my $hash_dump = pack 'L', $addr;

But unfortunately $hash_dump is not a HASH but just memory garbage.

How can I convert the address into a valid Perl HASH (or HASH ref)?

Replies are listed 'Best First'.
Re: How to turn "HASH(0x1234567)" into a real HASH
by ikegami (Patriarch) on Oct 13, 2017 at 17:23 UTC

    There's no telling if the hash still exists! If it doesn't, this could kill or corrupt your process. In other words, using this (or any other solution) is wrong!

    use Carp qw( croak ); use Inline C => <<'__EOS__'; SV* _newRV(UV addr) { return newRV((SV*)addr); } __EOS__ sub destringify_ref { $_[0] =~ /\(([^()]*)\)/ or croak("Invalid input"); return _newRV(hex($1)); } my %hash = ( a => 2, b => 3 ); my $ref = \%hash; $ref = "$ref"; $ref = destringify_ref($ref);
Re: How to turn "HASH(0x1234567)" into a real HASH
by LanX (Saint) on Oct 13, 2017 at 16:49 UTC
    It's not possible, to turn the stringified hash address into a reference.

    (At least not without meddling with internals and risking segfaults)

    My advice, keep the original reference.

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

      Thanks, that did it!

      my $hash = bless(\(0+hex $addr), "B::AV")->object_2svref;
        You are aware about the risks?

        Strings have no ref count!

        Cheers Rolf
        (addicted to the Perl Programming Language and ☆☆☆☆ :)
        Je suis Charlie!

Re: How to turn "HASH(0x1234567)" into a real HASH
by haukex (Archbishop) on Oct 14, 2017 at 18:04 UTC
    While debugging some code that's printing "HASH(0x9999999)" to stdout

    ikegami and LanX have given you some excellent answers. I am wondering why you don't just change the code you're debugging to use Data::Dumper or Data::Dump to show you the hashes? Even if you don't have full control over the code, Perl provides lots of ways to monkey-patch stuff in. If you could show some of the code that is generating this debug output, perhaps we could suggest a way to do that.