perl中的foreach

 

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值