The "foreach" loop iterates over a normal list value and sets the
variable VAR to be each element of the list in turn. If the variable is
preceded with the keyword "my", then it is lexically scoped, and is
therefore visible only within the loop. Otherwise, the variable is
implicitly local to the loop and regains its former value upon exiting
the loop. If the variable was previously declared with "my", it uses
that variable instead of the global one, but it's still localized to the
loop. This implicit localisation occurs *only* in a "foreach" loop.
复制代码
如果看不懂的话,本版精华区有中文版的大骆驼:
循环变量只在循环的动态或者词法范围内有效。如果该变量事先用 my 定义,那么它隐含地是在词法范围里。这样,对于任何在词法范围之外定义的函数它都是不可见的,即使是在循环里调用的函数也看不到这个变量。不过,如果在范围里没有词法定义,那么循环变量就是局部化的(动态范围)全局变量;这样就允许循环内调用的函数访问它。另外,循环变量在循环前拥有的值将在循环退出之后自动恢复。