8. Complex data structures - 5: Custom complex structure

You're are able now to create your own data structure using the datatypes you've seen. I made one for demonstration purposes only.
I also introduce you to the module Data::Dumper, which stringifies perl data structures, suitable for both printing and evaluation.

8.1 Create a custom complex structure

As already stressed in previous chapters, you can always use a reference in a list. So, let's define an array, containing a list.
@CS = 
(
'Reinier',
'www.reiniermaliepaard.nl',
'Perl',
);

print("Name: $CS[0]\n");
print("Website: $CS[1]\n");
print("Programming: $CS[2]");
Nothing new here. Let's extend this structure with an anonymous hash and an anonymous array reference.
@CS = 
(

{ # anonymous hash
first_name => 'Reinier',
last_name => 'Maliepaard',
},

'www.reiniermaliepaard.nl', # scalar value
['Perl', 'newLisp', 'Windows Commandline'] # anonymous array

);

print("First name: ${$CS[0]}{'first_name'}\n");
print("Last name: ${$CS[0]}{'last_name'}\n");
print("Website: $CS[1]\n");
print("Programming: @{$CS[2]}");
If you're aware of the internal structure of this array, then there is no problem. But the job can be done better, i.e. adding a label to the several fields.

8.2 A better custom complex structure

In Chapter 8 Hashes of Hashes, you read about an alternative way to construct a HoH. I use it now to create my Complex Structure.
%CS = ();
$CS{'Name'}{'first_name'} = 'Reinier';
$CS{'Name'}{'last_name'} = 'Maliepaard';
$CS{'Website'} = 'www.reiniermaliepaard.nl';
$CS{'Programming'}{'language'}->[0] = 'Perl';
$CS{'Programming'}{'language'}->[1] = 'newLisp';
$CS{'Programming'}{'language'}->[2] = 'Windows commandline';
This is equivalent to (see comments)
%CS = (
'Name' => { # hash of hash
'first_name' => 'Reinier',
'last_name' => 'Maliepaard',
},
'Website' => 'www.reiniermaliepaard.nl', # normal hash
'Programming' => { # hash of hash of arrays
'language' => ['Perl','newLisp','Windows Commandline'],
},
);
Most important, this code is readable, thanks to its descriptive labels.

8.3 Data::Dumper

Save the following code to e.g. Test.pl and run it in the terminal.
use Data::Dumper;
%CS = ();
$CS{'h1'} = 'h1_value';
$CS{'h2'}{'h2_key1'} = 'h2_key1_value';
$CS{'h2'}{'h2_key2'} = 'h2_key2_value';
$CS{'h3'}{'h3_key1'}->[0] = 'h3_key1_value1';
$CS{'h3'}{'h3_key1'}->[1] = 'h3_key1_value2';
$CS{'h3'}{'h3_key1'}->[2] = 'h3_key1_value3';
$CS{'h3'}{'h3_key2'}->[0] = 'h3_key2_value1';
$CS{'h3'}{'h3_key2'}->[1] = 'h3_key2_value1';
print Dumper(\%CS);
The result should be like:



In other words, the Module Dumper helps you printing a complex structure.