Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi PerlMonks


I have a function which has 2 inputs, one is a scalar and the other is a 1D array,

the function returns a 1D array,
##### sub mult { my ($a, @b) = @_; : : return @c; } ####

when the function is called $N times, say, I want to store the $N results in a 2D array
#### for $i (0..$N){ @results = mult($a,@b[$i]); } ####

but the above code gives me a very long 1D array, and the following code doesn't compile
#### for $i (0..$N){ @results[$i][] = mult($a,@b[$i]); } ####

trying to manipulate 2D arrays is wrecking my head,

and I'd appreciate any help.

Thanks

Damian

Replies are listed 'Best First'.
Re: creating 2D arrays
by japhy (Canon) on Jul 24, 2001 at 20:42 UTC
Re: creating 2D arrays
by wine (Scribe) on Jul 24, 2001 at 20:45 UTC
    You should take a look at perllol which contains everything you need to know about multdimensional arrays.

    Your last code should be changed to:

    for $i (0..$N){ $results[$i] = [ mult($a,@b[$i]) ]; }

    The [] is called an array reference constructor. Without this constructor your array is called in scalar context and it'll just return the number of elements it contains.

    Update Fixed my code, thanks to PrakashK, and remove the push.

    - Good luck

      Without this constructor your array is called in scalar context and it'll just return the number of elements it contains.
      Small correction.

      push does not evaluate its second argument in scalar context, rather it expects a list. Even if a scalar is pushed, it would be as if the second parameter is a one-element list.

Re: creating 2D arrays
by PrakashK (Pilgrim) on Jul 24, 2001 at 21:18 UTC
    As has already been explained by others, a reference must be used in place of an array itself.

    I'd like to add just one thing. For performance reasons, i'd rather change the sub mult to return the array reference rather than the array itself. Also, pass an array reference as the second param to mult instead of an array.

    sub mult { my ($a, $b) = @_; # dereference the array, process it and create a new array .... return \@c; } ## Assuming that the array @b is a 2D array too for $i (0..$N){ push @results, mult($a, $b[$i]); }