[ back to toc ]

array of array

Date: 2002/05/20 10:04

Q:
This is a simple script and attempt to put
@array = qw(this is a test)
in form of
$AoA = ([t,e,s,t],[i,s],[a],[t,e,s,t])
so i can call each element like
print $AoA->[0][0]; #for t ...
print $AoA->[0][1]; #for e

#!/usr/bin/perl
print "Content-type: text/html\n\n";

@array = qw(this is a test)
foreach (@array){ @array_elements = split //, $_ ;
push @$AoA , [join ',' , @array_elements] ;
}

print $AoA->[0][0];

but script unwork...and thanks for help...

by the way how can I view all other reply thread...

uatt
A:
First of all there is a missing ; after

@array = qw(this is a test)

Insreting the ; the program works, thopugh it may not do what you want. I
am not sure what you need, but I assume that you want AoA to be an array
of array (or sloppily said a two dimentioned array) containing the letters
of the sentence:

[ ['t','h','i','s'],['i','s'],['a'],['t','e','s','t']]

To do this you need the following:

#!/usr/bin/perl
print "Content-type: text/html\n\n";

# store the array of words
@array = qw(this is a test);
foreach (@array){
# 'my' is important to have a new array each time!!!!
# w/o 'my' the same array would be altered and $AoA[i]
# would be referencing the same array for (i=0 to 3)
my @array_elements = split //, $_ ;
# push the reference of the array on the array @AoA
push @AoA , \@array_elements;
}

# just print the array

print '[ ';
for $i (0..3){
print '[';
for $j (0..length($array[$i])-1){
print "'",$AoA[$i]->[$j],"'";
print ',' if $j < length($array[$i])-1;
}
print $i == 3 ? ']' : '],';
}
print " ]\n";
print $AoA->[0][0];

Well, I have put this script on server but this give me a blank page
#!/usr/bin/perl
print "Content-type: text/html\n\n";

@array = qw(this is a test);
foreach (@array){

my @array_elements = split //, $_ ;
push @AoA , \@array_elements;
}
print $AoA->[0][0]."\n";
print $AoA->[0][1]."\n";
print $AoA->[0][2]."\n";

Is there any thing wrong??
Q:
A:
AoA is an array and NOT a scalar referencing an array. Therefore $AoA-> is
undef. Thus $AoA->[0][0] is not the same as $AoA[0]->[0].

I hope I was clear enough to help you understand.

Regards,
Peter

[ back to toc ]