http://www.perlmonks.org?node_id=1025411


in reply to Re^2: Creating a unique variable type
in thread Creating a unique variable type

Technically, you are correct. An array value can only hold a scalar variable.

However, there are a couple of ways you can work around that. The most common is references. Instead of storing an array inside of another array, you store array references (which are scalar values) in your array.

The easiest way would be an array of array references:

my @array = ( "a", "b", "c" ); my $aref = [ "x", "y", "z" ]; push @array, $aref; # Current value for @array: #@array = ( # "a", # "b", # "c", # [ # "x", # "y", # "z" # ], # )

A brief example of using an array of array references:

#!/usr/bin/env perl use strict; use warnings; my @array; while (<DATA>) { chomp; my ($bool,$int) = split ","; # Take each ($bool,$int) tuple, and store it in an array reference # (By placing it in []) that we add to our array push @array, [ $bool, $int ]; } # Cycle through our array of array references and print them foreach my $entry (@array) { print "Bool: " . $entry->[0] . "\n"; # The -> dereferences our ar +rayref print "Int: " . $entry->[1] . "\n\n"; # The -> dereferences our ar +rayref } __DATA__ 0,14 0,7 1,13 0,3 1,9 0,2 1,1

Giving us the following output:

perl-fu@nexus:~/foo$ ./a_of_a.pl Bool: 0 Int: 14 Bool: 0 Int: 7 Bool: 1 Int: 13 Bool: 0 Int: 3 Bool: 1 Int: 9 Bool: 0 Int: 2 Bool: 1 Int: 1

For more information on nested data structures using references, you should check out perlreftut and perlref.

Christopher Cashell