in reply to Initializing multidimensional arrays

Do we have to initialise undef'd items one to four, when creating item five does that anyway?
$matrix[$_][4]=undef for(0..4);

Which leads to the next logical question, why do we need to do this at all? The creation of the highest-index item in the array creates all lower-index undefs anyway, and if you try to get item and it's not there, the array's going to return an undef anyway.

So the quickest way to do it is not do it at all.



($_='kkvvttuu bbooppuuiiffss qqffssmm iibbddllffss')
=~y~b-v~a-z~s; print

Replies are listed 'Best First'.
Re^2: Initializing multidimensional arrays
by cyocum (Curate) on Jun 01, 2005 at 12:37 UTC

    Cody is right on this. Just declare the array and the treat it as if it were a 5x5 matrix because as long as you treat it like one, it will be one.

    I guess you could do this:

    use strict; use warnings; my @matrix; $matrix[4][4];
    Perl will fill in the array with undef's for you.

    update: monarch is correct. It should be 4 because Perl defaults to an index of 0 for arrays unless you set the special variable $[ = 1.

      Just a question.. given that Perl arrays are 0 indexed would it be more correct to state:
      $matrix[4][4];
      . Also can't you do something like:
      $#matrix = 4;
      (not sure how you'd do the second dimension).

      Note that ; $matrix[4][4]; only fills out the first level with five elements and populates the last with an array reference. This is because the last subscript doesn't do anything. Just like

      if ($foo[100000] == 1) { ... }
      doesn't extend @foo to be 100001 elements. This is also why it gives a "useless use of array element in void context" warning.

      The first level is extended though, but only filled with undefs except for the fifth element which becomes an array reference, which will be empty because of the reason above, looking like

      [ undef, undef, undef, undef, [ undef, undef, undef, undef , undef ], ]
      Using the element in some way, not just using the value, like
      $matrix[4][4] = undef
      would fill out the array reference at index four in the first level, but the other levels would still be untouched, so you'd have a "half-expanded" 2D array, looking like
      [ undef, undef, undef, undef, [ undef, undef, undef, undef , undef ], ]
      This is why Cody Pendant uses the for loop.

      ihb

      See perltoc if you don't know which perldoc to read!

Re^2: Initializing multidimensional arrays
by Nkuvu (Priest) on Jun 01, 2005 at 16:06 UTC
    So the quickest way to do it is not do it at all.
    Or, if you are trying to reinitialize a 5x5 matrix that may have stuff in it: @matrix = ()