Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

RE: for loops

by nop (Hermit)
on Nov 01, 2000 at 21:28 UTC ( #39438=note: print w/replies, xml ) Need Help??

in reply to for loops

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

Replies are listed 'Best First'.
RE: RE: for loops
by mirey (Initiate) on Nov 02, 2000 at 04:51 UTC
    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;
Re^2: for loops
by hossman (Prior) on Oct 11, 2004 at 01:09 UTC
    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.

Re^2: for loops
by apotheon (Deacon) on Oct 11, 2004 at 00:58 UTC
    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

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (9)
As of 2020-05-29 21:15 GMT
Find Nodes?
    Voting Booth?
    If programming languages were movie genres, Perl would be:

    Results (171 votes). Check out past polls.