[Brisbane-pm] Passing a Two-Dimensional Array to a sub in Perl 5.8.6

Damian James djames at thehub.com.au
Wed Feb 21 18:40:10 PST 2007


On 22/02/2007, at 8:45 AM, Martin Jacobs wrote:
> Can you pass a two-dimensional array to a sub via a reference in  
> Perl 5.8.6?

Yes, the same way as any other reference.

> I'm operating under use strict.
>
> I have populated a 2D array called @Rain_series, like this...
>
> 	$array[0][0] = n
> 	$array[1][0] = m
>
> etc

I prefer to make every reference/dereference operation explicit,  
otherwise it's too easy to get confused. Therefore, this is:

   $array[0]->[0] = $n;
etc


>
> I checked that it has the right values in the right places by  
> printing off a few of them.
>
> I then compile all the arguments for the subroutine in a further  
> array called @Timestep_arguments, in which the sixth element is a  
> reference to my 2D array ( \@Rain_series ).
>
> I then passed @Timestep_arguments into a sub via a reference. The  
> sub looks like this...
>
> 	sub Rain_calculation (\@) {...}
> 	my $a	=	@_
> 	my @Rain_series = @$a[5]

This would be:

    my @Rain_series = @{ $a->[5] };

However, I strongly suggest that even though Perl has a prototype  
mechanism that can be used to enforce passing by reference, not using  
it. Seriously, it's probably what's causing your confusion here. Make  
all your refecence/dereference operations explicit. Also, $a is  
special, though not reserved in Perl. It's used by the sort()  
function, see the perldoc in perlfunc (perldoc -f sort).

So:

   sub Rain_calculation {
      my @stuff = @_;
      my @Rain_series = @{ $stuff[5] };

Cheers,
Damian



More information about the Brisbane-pm mailing list