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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.