
The Data Dumper module let's you visual how data is being interpretted by Perl. You may need to install the Data Dumper module on your system. Then, you will tell your Perl script to use the Data Dumper module.
use Data::Dumper;
As a very simple example, let's say your script has a variable ($foo) and you want to understand what value $foo contains. You can use Data Dumper to examine $foo.
print Dumper $foo;
In this example, Data Dumper let's you know that $foo contains a value of Hello World.
$VAR1 = 'Hello World';
Multiple variables can be evaluated, like this.
print Dumper ($foo, $bar);
Redirecting output to a file
Here is how you could redirect the dumper output to a file.
open(FH, ">", "example.txt") or die "cannot open example.txt $! \n";
print FH Dumper $foo;
close FH;
Hash
Let's say you have the following hash.
my %hash;
$hash{"employee"} = "John Doe";
Dumper can be used to display the structure of the hash. You will need to escape the % character, like this.
print Dumper \%hash;
Or you can wrap the hash in curley braces, like this.
print Dumper { %hash };
Which should return the following.
$VAR1 = {
'employee' => 'John Doe'
};
Hash Keys
Let's say you have the following hash. In this example, the hash has three keys (employee, id, department).
my %hash;
$hash{"employee"} = "John Doe";
$hash{"id"} = "123456";
$hash{"department"} = "Engineering";
Dumper can be used to only list the keys, like this.
use Data::Dumper;
print Dumper keys %hash;
Which should return the following.
$VAR1 = 'employee';
$VAR2 = 'id';
$VAR3 = 'department';
Redirecting output to a file
open(FH, '>>', foo.txt) or die "cannot open foo.txt $!";
print FH Dumper \%hash;
close FH;
Did you find this article helpful?
If so, consider buying me a coffee over at