Bootstrap FreeKB - Perl (Scripting) - Getting Started with Data::Dumper
Perl (Scripting) - Getting Started with Data::Dumper

Updated:   |  Perl (Scripting) articles

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. 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.

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my $foo = "Hello World";

print Dumper $foo;

 

The script should return the following stdout.

$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 Buy Me A Coffee



Comments


Add a Comment


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