2D array values got replaced error

K

Ken Soon

Hmm I go through a list
-7.9 2.1 F
-7.4 2.1 F
-6.9 2.1 F
-6.4 2.1 F
-5.9 2.1 P
-7.9 2.2 F
-7.4 2.2 F
-6.9 2.2 F
-6.4 2.2 F
-5.9 2.2 P
And i use the first and 2nd value as counters for my 2D array and third one
as the value
Storing using the following code: (I have cut away most codes for simplicity
sake)
while (<file1>)
{
if ($_ =~ /Site/)
{
@arr = split(/\s+/,$_);
$var1 = $arr[6];
$var2 = $arr[7];
$a[$var1][$var2] = $arr[9];
}
}

open (report, ">C://perl//report.txt") or die ("File Invalid");

Printing with the following code ($lastv is 2.2, $firstv is 2.1, $lasti
is -5.9, $firsti is -7.9)
for ($i=$lastv;$i>=$firstv ;$i=$i-0.1)
{
print $a[-0.01][2.2];
for ($j=$firsti;$j<=$lasti;$j=$j+0.5)
{
print report "$a[$j][$i],";
}
}
close report;

However, I got a matrix of just P printed out
And if I changed the last value from a P to an F, I get the matrix of F. It
is as though the last value assigned will replace all the values in the
array.
is there something I should be careful of when storing values in a 2D array?
 
A

anno4000

Ken Soon said:
Hmm I go through a list
-7.9 2.1 F
-7.4 2.1 F
-6.9 2.1 F
-6.4 2.1 F
-5.9 2.1 P
-7.9 2.2 F
-7.4 2.2 F
-6.9 2.2 F
-6.4 2.2 F
-5.9 2.2 P
And i use the first and 2nd value as counters for my 2D array and third one
as the value

You say counters (index is the common term), but the values are
not natural numbers. Arrays (in Perl and elsewhere) take integer
indices. A float point number is first converted to an integer.
Also, negative indices are special (they count from the end of the
array).
Storing using the following code: (I have cut away most codes for simplicity
sake)
while (<file1>)
{
if ($_ =~ /Site/)
{
@arr = split(/\s+/,$_);
$var1 = $arr[6];
$var2 = $arr[7];
$a[$var1][$var2] = $arr[9];
}
}

[more code with similar problems snipped]

That won't do what you want. Use a hash %a instead of the array @a.

Anno
 
K

Ken Soon

You say counters (index is the common term), but the values are
not natural numbers. Arrays (in Perl and elsewhere) take integer
indices. A float point number is first converted to an integer.
Also, negative indices are special (they count from the end of the
array).
Storing using the following code: (I have cut away most codes for
simplicity
sake)
while (<file1>)
{
if ($_ =~ /Site/)
{
@arr = split(/\s+/,$_);
$var1 = $arr[6];
$var2 = $arr[7];
$a[$var1][$var2] = $arr[9];
}
}

[more code with similar problems snipped]

That won't do what you want. Use a hash %a instead of the array @a.

Anno

Thks, changed to hash. A little bit more complex but it works :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top