but what is the problem in my code?
use strict;If you add 'use strict;' then it becomes very obvious there's something wrong with your code:
results in:use strict; use warnings;
Enter dimension : 5
see how the first row changes automatically...
Can't use string ("5
") as an ARRAY ref while "strict refs" in use at matrix_orig.pl line 25, <STDIN> line 1.
From there it's a small step to fix the attempt to define a multidimensional array on line 25:
- my @matrix = ( $n , $n ); + my @matrix;
Hmm. Actually the step is not that small. Let me try to explain. What you probably expect @array to contain is something like this:
However what you're actually creating is:@array = ( 1, 2, 3, <-- $i = 0 4, 5, 6, <-- $i = 1 7, 8, 9, <-- $i = 2 ^ ^ ^ | | | $j = 0 $j = 1 $j = 2 );
@array = ( [ 1, 2, 3 ], # <-- $i = 0 [ 4, 5, 6 ], # <-- $i = 1 [ 7, 8, 9 ], # <-- $i = 2 ^ ^ ^ | | | $j = 0 $j = 1 $j = 2 );
Please note the square brackets.
This is a typical 'array of array' data structure. Perl does not have any notion of a multidimensional array. Instead you create an array that has another array as one of it's members. To Perl the above data structure looks more like this:
Because of my @matrix = ( $n, $n); the array already contains 2 values before you start to populate it:@array = ([ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]); ^^^^^^^^^^^ ^^^^^^^^^^^ ^^^^^^^^^^^ $i = 0 $i = 1 $i = 2 # @array = <nested_array1>, <nested_array2>, <nested_array3>; # <nested_array1> = 1, 2, 3 # <nested_array2> = 4, 5, 6 # <nested_array3> = 7, 8, 9
@array = ( 5, 5 );
In line 28 you try to access the second dimension in the array, and perl complains that the already existing value '5' can not be used as a reference to another array.
!! This is your problem. Perl is unable to use the already existing value '5' as a reference into another array. !!
If you remove the attempt to define a multidimensional array, then @array looks like this instead:
$array[0] is an undefined value and perl will automagically create a nested array for you to store the first value@array = ();
next value ($i = 0, $j = 1, $k = 2)# $i = 0, $j = 0, $k = 1 @array = ( [ 1 ] );
next value ($i = 0, $j = 2, $k = 3)@array = ( [ 1, 2 ] );
next value ($i = 1, $j = 0, $k = 4)@array = ( [ 1, 2, 3 ] );
...and then everything starts to work as expected@array = ( [ 1, 2, 3 ], [ 4 ] );
In reply to Re^3: Multidimentioal array
by Monk::Thomas
in thread Multidimentioal array
by Subhrangshu Das
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |