References 2, Scratching at Complex Data Structures

Back again for another bite of the Alpaca? In order to take our references to the next level we need to start making arrays of arrays and arrays of hashes and other such complex arrangements. I’ll be starting of with  arrays as they are relatively simple and working my way up from there, step by step. The first task is to create a set of arrays to use and tie them together into a single array reference, like so:

#! /usr/bin/perl -w

use strict;

my @boys = qw/adam brian james ethan/;
my @girls = qw/sharon tracey linda louise/;
my @dogs = qw/rex rover lassie dino elsa/;

# pull them into 1 array ref

my @set = ( \@boys, \@girls, \@dogs );

foreach my $array_ref (@set){
	print "$array_ref\n";
}

When we run this program you get something you may not expect???

ARRAY(0x10082add0)
ARRAY(0x10082ae30)
ARRAY(0x10082afb0)

Why? because we asked the program to print out the array references and not the the array, $array_ref should be @{$array_ref} which we abbreviate to @$array_ref. After modification, the output looks like this:

adam brian james ethan
sharon tracey linda louise
rex rover lassie dino elsa

Before we dig any deeper, here is an example using the ‘Dump’ utility which outputs complex data into ‘human readable’ format – honest!

#! /usr/bin/perl -w

use strict;
use Data::Dumper;

my @boys = qw/adam brian james ethan/;
my @girls = qw/sharon tracey linda louise/;
my @dogs = qw/rex rover lassie dino elsa/;


# pull them into 1 array ref

my @set = ( \@boys, \@girls );

print Dumper(\@set);

this gives the following output:

$VAR1 = [
          [
            'adam',
            'brian',
            'james',
            'ethan'
          ],
          [
            'sharon',
            'tracey',
            'linda',
            'louise'
          ]
        ];

This entry was posted in Perl and tagged , , . Bookmark the permalink.

Leave a Reply

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