For loops allow you to do something a certain number of times in their most basic forms;
They take on the form:
for(initial_expression; test_expression; change_expression){
do_something;
}
This is equivalent to a while statement that looks like
initial_expression;
while(test_expression){
do_something;
change_expression;
}
This for loop will print the numbers 1 through 100 on separate lines;
for($i=1; $i<=100; $i++){
print "$i\n";
}
First the variable is set to 1, then it is tested to see if it is less than or equal to 100.
Then it is printed. Then the change expression is evaluated and $i is incremented by 1.
Then the text expression is evaluated again since $i is equal to 2 it is less than or equal to 100
so the loop is repeated until 100 is printed, $i is incremented to 101, $i is no longer less than or equal to 100 so the for loop is finished.
Now for foreach loops
In reply to for loops
by root
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|