Copying datastructures in Perl with Data::Dumper
August 29, 2004
Can you determine the output of the following Perl program without running it?
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $a = {foo => 1, bar => 3, quux => 5}; my $b = eval Dumper $a;
print Dumper $a; print Dumper $b;
If you expected something like this:
$VAR1 = {
'bar' => 3,
'quux' => 5,
'foo' => 1
};
$VAR1 = {
'bar' => 3,
'quux' => 5,
'foo' => 1
};
then I’m afraid I’m going to dissapoint you. The actual output is:
$VAR1 = {
'bar' => 3,
'quux' => 5,
'foo' => 1
};
$VAR1 = undef;
I spent the entire evening yesterday trying to figure out why this did not work as I expected. The Data::Dumper manpage says you can do this by eval-ing the string returned by Dumper().
If you remove the “use strict;” line from the program above you’ll get the behaviour you most likely expected. I’ll leave the “how?” as an excersise for the reader.
Leave a Reply