How to dump variables in perl
How to dump variable in perl
Have you guys ever needed to dump variables in perl and see its exact contents? I had and was really tricky. The print
function is alright for printing scalar variables, but when you try to print a hash and maybe with multiple levels you start to have headaches trying to read the content…
So, there’s a nifty perl module that you can use to dump the content of an entire array or hash, this is by using Data::Dumper
. Its a core perl module, so you should already have it, however cpan
would easily install this for you if really need it.
So to install Data::Dumper you can easily run:
1 |
cpan install Data::Dumper |
wait for it to finish and you can then start using it in your code.
A nice little example on how to use this is bellow:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#!/usr/bin/perl use Data::Dumper; %foo = (); $foo{'something1'} = 'something else 1'; $foo{'something2'} = 'something else 2'; $foo{'something3'} = 'something else 3'; $foo{'something4'} = 'something else 4'; print Dumper(%foo); |
The output would look similar to:
1 2 3 4 5 6 7 8 |
$VAR1 = 'something3'; $VAR2 = 'something else 3'; $VAR3 = 'something1'; $VAR4 = 'something else 1'; $VAR5 = 'something4'; $VAR6 = 'something else 4'; $VAR7 = 'something2'; $VAR8 = 'something else 2'; |
On test cases it should give you better information to see what is going on and to help you fix the code.
You can also use it in loops or even use OO by creating objects, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#!/usr/bin/perl use Data::Dumper; %foo = (); $foo{'something1'} = 'something foo else 1'; $foo{'something2'} = 'something foo else 2'; $foo{'something3'} = 'something foo else 3'; $foo{'something4'} = 'something foo else 4'; %bar = (); $bar{'something1'} = 'something bar else 1'; $bar{'something2'} = 'something bar else 2'; $bar{'something3'} = 'something bar else 3'; $bar{'something4'} = 'something bar else 4'; # OO usage $d = Data::Dumper->new([%foo, %bar]); print $d->Dump; |
Hope it helps. Cheers.