Using the Data::Dumper module to debug your Perl scripts

If you’re ever writing a Perl script that contains fairly complicated data structures (multi-dimensional arrays, hashes of arrays, etc), or you’re debugging code that contains complicated objects, it may be helpful to view the current state of those data structures in their entirety.

This is easy to do with Data::Dumper. Although the features the module provides are fairly complex, it’s easy to use it to just print out the contents of something. Do do this, you’ll first need to import the module with ‘use Data::Dumper;’. Then, to dump the data in an array(for example), simply do ‘print Dumper(@array)’.

As an example, the following code:

my @names = ([“Joe”,”Smith”],[“John”,”Miller”],[“Steve”,”Stevenson”]);

print Dumper(@names);

Will print the below:

$VAR1 = [

‘Joe’,

‘Smith’

];

$VAR2 = [

‘John’,

‘Miller’

];

$VAR3 = [

‘Steve’,

‘Stevenson’

];

In addition to its use in debugging, the output of this function can also be passed to ‘eval’ to recreate your original data structure

Leave a Reply

Your email address will not be published. Required fields are marked *