The first example is the
C style
for loop with initialisation, condition and post-loop action in the preceding parens
1. As for the second example that is the more natural way of iterating over lists in
perl - it takes a list and aliases the topic (
$_ by default) to each element per iteration. However in your second example, you create a list of values from
0 to the size of the array, as opposed to the
last index of the array i.e
for(0 .. $#array) { ... }
This style is definitely the common way of iteratively accessing the elements of an array, but the more idiomatic approach of iterating over an array, when the index isn't needed, is simply
for(@array) { ... }
That works because an array in a list context flattens to a list (as opposed to in scalar context, where it yields the number of elements it contains, which is almost always
$#array + 1) providing
for with a list to iterate over.
See. perlsyn for more info.
HTH
_________
broquaint
1 internally, I believe this is implemented as a while(COND) { ... } continue { ... }
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.