in reply to Re: Multidimentioal array
in thread Multidimentioal array
Thanks 1nickt ... learnt a new trics... but what is the problem in my code? did u understand anything?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Multidimentioal array
by Monk::Thomas (Friar) on Jul 10, 2015 at 09:05 UTC | |
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:
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:
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:
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:
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 next value ($i = 0, $j = 1, $k = 2) next value ($i = 0, $j = 2, $k = 3) next value ($i = 1, $j = 0, $k = 4) ...and then everything starts to work as expected | [reply] [d/l] [select] |