November 2013 Archives

Debuging method for perl Complex data structures

For complex data structures (references, arrays and hashes) you can use the Data::Dumper

use Data::Dumper qw(Dumper);

print Dumper \@an_array;
print Dumper \%a_hash;
print Dumper $a_reference;

These will print something like this, which helps understand the content of the variables, but shows only a generic variable name such as $VAR1 and $VAR2.

$VAR1 = [
       'a',
       'b',
       'c'
     ];
$VAR1 = {
       'a' => 1,
       'b' => 2
     };
$VAR1 = {
       'c' => 3,
       'd' => 4
     };

I'd recommend adding some more code and printing the name of the variable like this:

print '@an_array: ' . Dumper \@an_array;

to gain:

@an_array: $VAR1 = [
        'a',
        'b',
        'c'
      ];

or with Data::Dumper like this:

print Data::Dumper->Dump([\@an_array, \%a_hash, $a_reference],
[qw(an_array a_hash a_reference)]);

getting

$an_array = [
            'a',
            'b',
            'c'
          ];
$a_hash = {
          'a' => 1,
          'b' => 2
        };
$a_reference = {
               'c' => 3,
               'd' => 4
             };

From:

Hello Perl World

I will record the fun and valued things during my advanture of perl learning.

About flymike

user-pic Keep it simple, stupid.