Gossamer Forum
Home : General : Perl Programming :

How to make an array of an array using split?

Quote Reply
How to make an array of an array using split?
Let’s say you have an array with two entries using split

$t1 = "ab";

@a = split((//, $t1)

= ["a", "b"]

And you want to tack on a new text to make an array of arrays from the original array:

$t2 = "cd";

@a ???= split((//, $t2)

= [["a", "b"], ["c", "d"]]

How do you do this with the split command, please?
Quote Reply
Re: [mpalmer] How to make an array of an array using split? In reply to
Arrays and array references are very different. You are mixing references with non references.

Anyhow, if you create an array using split (assume $var is "abc"):

Code:
my @array = split //, $var;

...so now you have an array with 3 elements containing a, b and c. To create an array reference of array references from that and at the same time split another variable you'd do:

Code:
my $array_reference = [ \@array, [ split //, $var ] ];

...that would leave you with:
Code:
[ ['a', 'b', 'c'], ['a', 'b', 'c'] ]

Last edited by:

Paul: Mar 11, 2003, 4:23 PM
Quote Reply
Re: [Paul] How to make an array of an array using split? In reply to
THANK YOU VERY MUCH!

My goal here is to take a text and split it up in several different ways (like maybe 20), saving each way in a single matrix, or array of arrays.

Is there a way to leave out having to make the first array so that I could have this run in a loop that fills up the array with the different ways of splitting? Something like

my $array_reference = [split //, $var, [ split //, $var ] ];


Also, how could you get a count of the total # of elements in the array of arrays?

(6 in your example.)
Quote Reply
Re: [mpalmer] How to make an array of an array using split? In reply to
You could do:

Code:
my $ref = [ [ split //, $var ], [ split //, $var ] ];

For the count, try:

Code:
my $total = 0;
for (@$ref) {
$total += scalar @$_;
}