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

Jacinta Richardson jarich at perltraining.com.au
Thu Feb 22 18:19:46 PST 2007


As many people have said, subroutine prototypes are a bad idea.  However I'm not
sure what's causing your problem.  I've tried to duplicate your code from what
you've written (with some minor changes to make it compile) and I've come up
with the following:

#!/usr/bin/perl -w
use strict;
use Data::Dumper;

# Some input data
my @array;
$array[0] = [ 1 .. 10 ];
$array[1] = [ 'a' .. 'g' ];

# Define my subroutine (I have to do it up here to avoid prototype warning)
sub test (\@) {
        my ($a) = @_;
        my @rain = @{$a->[5]};

        print '-' x 50, "\n";
        print "rain[0][1]: ", $rain[0][1], "\n";  # prints '2'
        print "rain[1][1]: ", $rain[1][1], "\n";  # prints 'b'

        print '-' x 50, "\n";
        print "a: ", Dumper $a;
        print '-' x 50, "\n";
        print "rain: ", Dumper \@rain;
        print '-' x 50, "\n";
}

# Create list of arguments and call test sub
my @args = (11 .. 15, \@array);
test(@args);


Unfortunately this works perfectly.  @rain appears to be getting full access to
what we defined in @array as expected.  So I must have missed something from
what you wrote.  The same effect can be achieved without prototypes as follows:

#!/usr/bin/perl
#use strict;
use Data::Dumper;

my @array;
$array[0] = [ 1 .. 10 ];
$array[1] = [ 'a' .. 'g' ];

my @args = (11 .. 15, \@array);

test(\@args);

sub test {
        my ($a) = @_;
        my @rain = @{$a->[5]};

        print '-' x 50, "\n";
        print "rain[0][1]: ", $rain[0][1], "\n";
        print "rain[1][1]: ", $rain[1][1], "\n";

        print '-' x 50, "\n";
        print "a: ", Dumper $a;
        print '-' x 50, "\n";
        print "rain: ", Dumper \@rain;
        print '-' x 50, "\n";
}


Alternately, depending on what you're doing, you can pass test() the array
directly rather than as a reference:

test(@args);

sub test {
	# Must use better variable names
	my ($a, $b, $c, $d, $e, $rain) = @_;
	my @rain = @$rain;
	...
}

Be aware that with all of these methods, if you manipulate the sub-arrays in
@rain you are changing that data for your whole program.

If the above doesn't help you, please feel free to modify what I've written to
more accurately reflect your problem so we can play around with it a bit.

All the best,

	Jacinta

-- 
   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +61 3 9354 6001        |
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
 (il),-''  (li),'  ((!.-'             |   www.perltraining.com.au   |


More information about the Brisbane-pm mailing list