J
jerrykrinock
I need to pass an array of arrays from a function, but I can't make an
array of arrays work. Actually, I've got better results making an
array of array references. Here's what I've done:
#!/usr/bin/perl
my @array ;
my @row ;
@row = ('a00', 'a01') ;
push (@array, \@row) ;
@row = ('a10', 'a11') ;
push (@array, \@row) ;
@row = ('a20', 'a21') ;
push (@array, \@row) ;
# In real life I will return @array to the caller, but the
# problem can be demonstrated without doing that...
my $nRows = @array ;
foreach my $array_ref (@array) {
# $array_ref is a reference to an array (row)
# Dereference it.
my @row = @$array_ref ;
# Print each element (column) separated by spaces
foreach my $element (@row) {
print "$element ";
}
# Next row, new line
print "\n" ;
}
My expected result is:
a00 a01
a10 a11
a20 a21
but the actual result is:
a20 a21
a20 a21
a20 a21
What am I doing wrong?
Thanks,
Jerry Krinock
array of arrays work. Actually, I've got better results making an
array of array references. Here's what I've done:
#!/usr/bin/perl
my @array ;
my @row ;
@row = ('a00', 'a01') ;
push (@array, \@row) ;
@row = ('a10', 'a11') ;
push (@array, \@row) ;
@row = ('a20', 'a21') ;
push (@array, \@row) ;
# In real life I will return @array to the caller, but the
# problem can be demonstrated without doing that...
my $nRows = @array ;
foreach my $array_ref (@array) {
# $array_ref is a reference to an array (row)
# Dereference it.
my @row = @$array_ref ;
# Print each element (column) separated by spaces
foreach my $element (@row) {
print "$element ";
}
# Next row, new line
print "\n" ;
}
My expected result is:
a00 a01
a10 a11
a20 a21
but the actual result is:
a20 a21
a20 a21
a20 a21
What am I doing wrong?
Thanks,
Jerry Krinock