CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Strings and Columns?

 



patyr
Deleted

Mar 24, 2000, 6:35 AM

Post #1 of 2 (592 views)
Strings and Columns? Can't Post

How can I get the number of strigs and columns of a two dimensional array?
I'm gonna use it in a FOR!
Thanks,
Patyr


japhy
Enthusiast

Mar 24, 2000, 7:14 AM

Post #2 of 2 (592 views)
Re: Strings and Columns? [In reply to] Can't Post

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.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives