Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected Data::Dumper::Dumper result

Tags:

perl

Why does here Data::Dumper::Dumper print the $VAR1->{'AA'}[2] instead of { 1 => 6 }?

#!/usr/bin/env perl
use warnings;
use strict;
use 5.10.0;

my @a = ( 'a', 'b', { 1 => 6 } );
my %h = (
    'AA' => [ @a ],
    'BB' => [ @a ],
);


say $h{BB}->[2]{1};

use Data::Dumper;
say Dumper \%h;

Output:

6
$VAR1 = {
        'AA' => [
                    'a',
                    'b',
                    {
                    '1' => 6
                    }
                ],
        'BB' => [
                    'a',
                    'b',
                    $VAR1->{'AA'}[2]
                ]
        };
like image 990
sid_com Avatar asked Aug 06 '14 09:08

sid_com


2 Answers

In your example $VAR1->{'AA'}[2] and $VAR1->{'BB'}[2] are references to the same hash.

Data::Dumper does not want to print a variable more than once. This behaviour represents the data structure more faithfully, and it avoids any infinite loop it might encounter. e.g.:

my $loop;
$loop = { 1 => \$loop };
print Dumper $loop;

Output is

$VAR1 = {
     '1' => \$VAR1
};
like image 139
Ckln Avatar answered Sep 27 '22 22:09

Ckln


Data::Dumper has configuration variables that can change the behavior that avoids printing a reference more than once.

  • $Data::Dumper::Deepcopy or $OBJ->Deepcopy([NEWVAL])

    Can be set to a boolean value to enable deep copies of structures. Cross-referencing will then only be done when absolutely essential (i.e., to break reference cycles). Default is 0.

To integrate this into your script just localize the variable:

say do {
    local $Data::Dumper::Deepcopy = 1;
    Dumper \%h;
};

Outputs:

$VAR1 = {
          'AA' => [
                    'a',
                    'b',
                    {
                      '1' => 6
                    }
                  ],
          'BB' => [
                    'a',
                    'b',
                    {
                      '1' => 6
                    }
                  ]
        };
like image 26
Lajos Veres Avatar answered Sep 27 '22 21:09

Lajos Veres