FreeKB - Perl Getting Started with Data::Dumper
Perl - Getting Started with Data::Dumper

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;

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 01e5a in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |