Click to See Complete Forum and Search --> : help with arrays in Perl


lnong
07-10-2003, 05:18 PM
I want to create an array of arrays of strings. Here's what I tried doing:

my (@arrayOfArrays, @array);
This is inside a FOR Loop
{
@array = (@array, "myString");
@arrayOfArrays = (@arrayOfArrays, \@array);
}

That should create an array of array references, where each reference points to an array of increasing size (i.e. one more element than the previous array).
Now, what if I want to add a string value directly to one of the subarrays, say the 5th array (index=4). How would I do it? Is this how?

$arrayOfArrays->[4] = ($arrayOfArrays->[4], "2ndString");

Probably not, because it's not working. Please help with this. Thanks.

Jeff Mott
07-10-2003, 09:47 PM
@array = (@array, "myString");
@arrayOfArrays = (@arrayOfArrays, \@array);There is a push function built-in to Perl to simplify (and moderately speed up) this process.push(@array, "myString");
push(@arrayOfArrays, \@array);where each reference points to an array of increasing sizeActually, they all point to the same array. A reference does not create a copy of the array.$arrayOfArrays->[4] = ($arrayOfArrays->[4], "2ndString");The left side of this assignment is in scalar context, while the right side is in list context. I'm guessing that with this example "2" is the value being assigned. Because a list in scalar context returns the number of elements in that list. You again would want to use push here.push($arrayOfArrays[4], "2ndString");