Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Multidimensional Arrays

Status
Not open for further replies.

lmbylsma

Programmer
Nov 11, 2003
33
US
I'm not understanding how to create a multidimensional array by reading lines from a file.

So say I have a file like this:

0 1 2 3
4 5 6 7
8 9 10 11

With lines of numbers separated by tabs.

I would have something like this to read the lines from the file and put each line into the array:

my @Array;

while (<>) {

chomp;
push @Array, &quot;$_&quot;;
}

So that results in an array with 3 strings stored in it, tabs and all. But what I really want is to store each number as a separate element in the array so I can refer to each number using references such as @Array[0][1], @Array[2][3], etc. What do I do next to convert it to this form? Or perhaps even better to put it in the right form in the first place?

I tried some things with split /\t/ but wasn't able to get it right.

-Lauren
 
You will have to start using references and creating anonymous arrays to build this type of structure. It would look something like this:

use strict;
open (IN, &quot;$file&quot;);
my @array;
while (<IN>) {
push @array, [split/\s+/]; #create anonymous array inside of @array
}
print $array[1][1]; #prints the value 5


The following links are good documentation on references and creating mulitdimensional data structures.

 
Change the split/\s+/ parameter to \t or whatever you are using. I copied your list of values into a text file but they came out being separated by just spaces.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top