1

Data::Dumper doesn't seem to expand references that are hash keys, and I can't figure out what settings to change to make it do so. Is this even possible?

Example code:

#!/usr/bin/perl
use Data::Dumper;
@array = ('foo', 'bar');
$arf = \@array;
%hash1 = ( 'baz' => $arf );
%hash2 = ( $arf => 'baz' );
print Dumper(@array); print "\n";
print Dumper(%hash1); print "\n";
print Dumper(%hash2);

This outputs:

$VAR1 = 'foo';
$VAR2 = 'bar';

$VAR1 = 'baz';
$VAR2 = [
          'foo',
          'bar'
        ];

$VAR1 = 'ARRAY(0x8be1b04)';
$VAR2 = 'baz';

But I would like something to get the output:

$VAR1 = 'foo';
$VAR2 = 'bar';

$VAR1 = 'baz';
$VAR2 = [
          'foo',
          'bar'
        ];

$VAR1 = [
          'foo',
          'bar'
        ];
$VAR2 = 'baz';
onigame
  • 214
  • 3
  • 10
  • 7
    That's because you can't have references as hash keys. They will always be stringified. Data::Dumper is giving you the correct results. – Miller Jul 30 '14 at 01:00
  • Ah, I see. Is there a way to convert the stringified hash keys back to the reference? – onigame Jul 30 '14 at 01:05
  • 1
    Not in any practical way. Yes, the string `ARRAY(0x8be1b04)` obviously has some relation to where the original reference was pointing. However, at this point the string should just be considered a string and any reverse engineering is going to be difficult and/or fragile. – Miller Jul 30 '14 at 01:14
  • You cannot get back the reference back from the string because it might not even exist anymore. You only know that that where the reference was at the time of stringification. – Steffen Ullrich Jul 30 '14 at 06:07
  • @SteffenUllrich, actually if you know the referred thing still exists (hasn't been garbage collected), [it is possible to reclaim the reference back from the string](http://gist.github.com/afb2840c345afcbb0305). However, anyone feeling the need to apply this sort of technique to their code has probably gone wrong somewhere. – tobyink Jul 30 '14 at 10:46
  • @tobyink: yes, I should have said that there is no guarantee that you might get it back because it might not exist any more. The string representation does not cause the reference counter to increase so the reference might vanish even if their string representation is still there. – Steffen Ullrich Jul 30 '14 at 21:44

1 Answers1

0

Simplistically, change

%hash2 = ( $arf => 'baz' );

to

@hash2 = ( $arf => 'baz' );

Of course, then it's no longer a hash, but an array.

Quantum Mechanic
  • 625
  • 1
  • 6
  • 20