Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

for loops

by root (Monk)
on Nov 05, 1999 at 05:08 UTC ( #952=perltutorial: print w/replies, xml ) Need Help??

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){

This is equivalent to a while statement that looks like


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

Replies are listed 'Best First'.
RE: for loops
by nop (Hermit) on Nov 01, 2000 at 21:28 UTC
    When using multiple initializations in a for loop, I found that scoping didn't work as I expected it would. For example, in this fake snippet
    use strict; ### this code contains an error for (my $i=1, my $j = $i + 100; $i<50; $i++, $j++) { print "i=$i j=$j hello!\n"; }
    the line
    my $j = $i + 100;
    generates an error because $i doesn't exist yet. Not a big deal, and trivial to work-around, but can someone explain why scoping works this way here? nop
      I do not think you are looking at a scope issue. You are including code in the defenition of your for loop. Try this: for($i; $i < 50; $i++) { $j = $i + 100; $j++; print "i=$i j=$j hello!\n"; } Another question would be why do you have $j = $i + 100; and $j++; instead combine them the following way $j = $i + 101;
      can someone explain why scoping works this way here?

      That question implies that the scoping works differently elsewhere -- it doesn't. you get that error regardless of the for loop...

      laptop:~> perl -Mstrict -e 'my $i=1, my $j=$i+1; print $i + $j;' Global symbol "$i" requires explicit package name at -e line 1. Execution of -e aborted due to compilation errors.

      ...the behavior of the comma oporator is not changed by being used in a for loop.

      Because the value of $j has no bearing on the test expression, it doesn't belong in the initial and change expressions of the for statement. As such, they should be included in the set of code executed by the loop.

      - apotheon
      CopyWrite Chad Perrin
Re: for loops
by Willman023 (Scribe) on Nov 07, 2002 at 16:30 UTC
    I think it would be useful to show an additional way the for loop can be used. Although the C-like for loop can do the same thing, I find myself using the one below more and more.

    for $countdown (10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 'Liftoff!') { print $countdown, "\n"; } for $y (0..$x) { print $array[$y], "\n"; } for (@array) { s/value1/value2/ } # Substitues value2 for value 1.


    A reply falls below the community's threshold of quality. You may see it by logging in.
RE: for loops
by Falthor (Initiate) on Jun 02, 2000 at 02:47 UTC
    just wondering here... if a value is not assigned to a variable at the startup does that mean that the value is automatically assigned to 0 ? Jason Temple AKA Falthor Assistant Operartions Manager Neurogames

      No. An unassigned variable contains the special value undef. This will evaluate as false under some circumstances. 0 (and, indeed, '0') also evaluates as false, which is where the confusion arises.


      European Perl Conference - Sept 22/24 2000
      Now how does it know to print on the next line ? do we specify anything or it just does it ?
        Suggest you re-visit the String scalars section. The \n is a newline character to be printed. Thus after each value, a newline is printed (CR/LF) so the next print will start on a new line
Re: for loops
by xalphabetx (Initiate) on Mar 21, 2002 at 06:49 UTC
    okay so just trying to understand the logic of these new commands (for me) for($i=1; $i<=100; $i++) okay so now I understand how this line is read and the syntax but if the line starts over at the end doesnt $i return to the value of 1? I know already that this code works obviously but howcome? in my brain it says it should be starting $i back to a value of $i=1 and the evaulating the rest again so I guess Im just not getting it any help??
      $i++ is the equivalent of
      where the = is an operator. It's not just sitting there, like it does in math, saying "these two things are equal"; it tells Perl to make the two things equal. So here it's saying "take the current value of $i and add 1, and make that the new value of $i." Then the for loop continues with the new value of $i. This happens each time the loop runs, until $i reaches 100.

      "Abby-somebody. Abby-normal."
      Young Frankenstein
      On second and following iterations, the for loop ignores the initial assignment of value to $i and uses the incremented value (or decremented, if you use a decrement operator instead of an increment operator) instead. The $i=1 assignment happens once, and once only, in for($i=1; $i<=100; $i++).

      - apotheon
      CopyWrite Chad Perrin

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perltutorial [id://952]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2023-03-22 05:26 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (60 votes). Check out past polls.