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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading a 2-D array with File handle

Status
Not open for further replies.

ratz

Technical User
Oct 27, 2000
7
0
0
GB
I have a script that works fine when the data is stored in the same file as the script.
The data is a 2-D array.

because the file is quite large, I stored it in a seperate .txt file to read only from the script.

But the script does not 'see' the data as a 2-d array, as it can't access specific elements.

I have scaled it down to show you what I mean:
Here data in ray.txt
[1,10,100,"a",5,2],
[2,10,100,"b",5,2],
[3,10,100,"c",5,2],
[4,10,100,"d",5,2],
[5,10,100,"e",5,2],

Here is the Script that reads from it:
$TMP='c:/scripts/ray.txt';

open (FILE,$TMP) | | die "cannot open file for read";
while (<FILE> )
{
push(@RAY,$_);}
close FILE;
#test if array has been created.
print &quot;@RAY\n&quot;; #prints OK
$num=scalar(@RAY); #returns 5
print &quot;$num\n&quot;;
$row=($RAY[1]->[3]);#does not work
print &quot;$row\n&quot;;
my $var=($RAY[1]->[2]);#does not work
print &quot;$var\n&quot;;

The exact script works OK if the data is in the same file as the script, once the data is read, the script should work as normal??right?

Sher
 
to be honest I didn't know that trick worked at all, would guess that you've found a feature there...

have you considered [tt]split[tt]ting the data in the usual way?

Mike
michael.j.lacey@ntlworld.com
 
Hai,
The data you have in ray.txt is 6 entries in a row. So what do you mean by 2-D array???.

Give this code a try. Hope it works. $my2darr is hash, whose keys are 1,2,3,... . And the values are the rest of the entries on each line. This represents a 2D array.
To manipulate this hash use $my2darr->{key}, unlike $my2darr{key}.

use Data::Dumper;
$Data::Dumper::Indent=1;
my $my2darr ={};
while (<DATA>)
{
chomp;
s/(\[|\])//g;
split(&quot;,&quot;,$_,9999);
push(@{$my2darr->{$_[0]}},@_[1..$#_]);
}
print Data::Dumper->Dump([$my2darr],['MY2DARR']);
__DATA__
[1,10,100,&quot;a&quot;,8,10]
[2,10,100,&quot;b&quot;,8,10]
[3,10,100,&quot;c&quot;,8,10],
[4,10,100,&quot;d&quot;,8,10],
[5,10,100,&quot;e&quot;,8,10],
 
think you're missing the point a bit here japh - original poster said that it worked *fine* if data was in same file as script, problem was with data in separate file....

Mike
michael.j.lacey@ntlworld.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top