While writing software, is sometimes useful to dump the content of a variable. In this post we will see a simple way to do it in Perl.

If you want to dump the content of a string variable, there are no problems as you could simply do the following (throughout this post I will use “die” to output the content of a string, but you can use any method you want):

my $MyVar = "Mark";

die $MyVar;

The situation is slightly more complicated when you are working with arrays and hashes. Of course you can iterate each single item of the array or hash and print the value and, in case of hash, you may also want to print the key.

But there is a simpler way… You can use the Data::Dumper package.

First example: dump the content of an array:

use Data::Dumper;

my @names = ("Matthew", "Luke", "Mark", "John", "Paul");
my $str = Dumper(@names);
die $str;

$VAR1 = 'Matthew'; $VAR2 = 'Luke'; $VAR3 = 'Mark'; $VAR4 = 'John'; $VAR5 = 'Paul';

Second example: dump the content of an hash:

use Data::Dumper;

my %names_hash = ("person1" => "Matthew",
"person2" => "Luke",
"person3" => "Mark",
"person4" => "John",
"person5" => "Paul",

my $str = Dumper(%names_hash);
die $str;

$VAR1 = 'person3'; $VAR2 = 'Mark'; $VAR3 = 'person4'; $VAR4 = 'John'; $VAR5 = 'person5'; $VAR6 = 'Paul'; $VAR7 = 'person2'; $VAR8 = 'Luke'; $VAR9 = 'person1'; $VAR10 = 'Matthew';

Hope this helps…