现在的位置: 首页 > 综合 > 正文

perl中的foreach

2013年10月27日 ⁄ 综合 ⁄ 共 725字 ⁄ 字号 评论关闭

 

From Wiki

 

For each (or foreach) is a computer language idiom for traversing items in a collection. Foreach is usually used in place of a standard for statement. Unlike other for loop constructs, however, foreach loops [1] usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages an iterator, even if implicit, is often used as the means of traversal.

 

 

#! /usr/bin/perl -W
use strict;

my @array = (1 .. 9);

my $num;
foreach $num(@array) {
    $num **= 2;
}
print "@array/n";

输出如下:
1 4 9 16 25 36 49 64 81

在这里很重要的一点在于,控制变量$num代表着@array中的一个特定项目。如在一个foreach结构的主题内修改控制变量的值,会同时改变控制变量当前代表的那个@array元素。
因此每次执行foreach内的代码时,@array的当前值都会发生变化。 

 

 

 

http://en.wikipedia.org/wiki/Foreach

抱歉!评论已关闭.