
japhy
Enthusiast
Mar 24, 2000, 7:14 AM
Post #2 of 2
(1658 views)
|
I think you're thinking in a C kind of loop. In Perl, you don't need to iterate over an array by element number, you can iterate over the actual elements: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> # what a C programmer might do... for ($i = 0; $i = $#array; $i++) { playwith($array[$i]); } # what a Perl programmer would do... for (@array) { playwith($_); } </pre><HR></BLOCKQUOTE> Read about for (or foreach) loops in the perlsyn documentation (comes with Perl, and is also on this web site). To work with two dimensional arrays, do something like: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> for $out (@array) { for $in (@{ $out }) { playwith($in); } } </pre><HR></BLOCKQUOTE> To get the number of elements in an array, evaluate @array in scalar context: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $size = @foo; </pre><HR></BLOCKQUOTE> To get the LAST INDEX of an array (which is the number of elements, minus one), use the $#array variable: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $lastindex = $#bar; </pre><HR></BLOCKQUOTE> Arrays are discussed in the perldata documentation. Multidimensional arrays are discussed in perlref, perllol, and perldsc. The perlreftut documentation (which comes with either 5.005_03 or the newest Perl, 5.6) might be good for you, too. If that's not on this site, perhaps it can be gotten from the http://www.perl.com/ web site.
|