Chinaunix

标题: foreach遍历数组是顺序的吗? [打印本页]

作者: yjh777    时间: 2009-09-28 16:25
标题: foreach遍历数组是顺序的吗?
现在要 foreach 遍历一个数组,同时要取对应的下标,

请教各位大侠 foreach 遍历的时候,是不是顺序的?下面这种写法能行吗?

foreach $item (@list) {
    printf("%d -> $item\n", $i++);
}


------------------------------------------
标准答案在9楼。谢谢关注。

[ 本帖最后由 yjh777 于 2009-10-14 13:00 编辑 ]
作者: Perl_Er    时间: 2009-09-28 16:30
标题: 回复 #1 yjh777 的帖子
应该是的,你自己试一试不就好了,
作者: 兰花仙子    时间: 2009-09-28 16:32
原帖由 yjh777 于 2009-9-28 16:25 发表
现在要 foreach 遍历一个数组,同时要取对应的下标,

请教各位大侠 foreach 遍历的时候,是不是顺序的?下面这种写法能行吗?

foreach $item (@list) {
    printf("%d -> $item\n", $i++);
}


自己测试一下咯。。。

  1. # perl -e '
  2. > @list = (4,3,2,1,0);
  3. >
  4. > foreach $item (@list) {
  5. >     printf("%d -> $item\n", $i++);
  6. > }'
  7. 0 -> 4
  8. 1 -> 3
  9. 2 -> 2
  10. 3 -> 1
  11. 4 -> 0
复制代码

作者: yjh777    时间: 2009-09-28 16:45
谢谢两位,试可仍不敢肯定所以再问确认一下

不过刚才还是范了个错误,把 my $i 声明到循环体里面了,结果下标全是0 ,,
作者: blackold    时间: 2009-09-28 18:29
yes
作者: PeterKalven    时间: 2009-10-12 11:07
标题: 回复 #3 兰花仙子 的帖子
学习了。
作者: ermu    时间: 2009-10-13 01:48
好像foreach出来的顺序并不是数组的0到n吧?
作者: HongLian3    时间: 2009-10-13 09:29
标题: 回复 #1 yjh777 的帖子
可以的,不确定的时候可以多执行代码来试试,熟悉测试也很重要哇~
作者: yecheng_110    时间: 2009-10-13 13:44
perlsyn

Foreach Loops

The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn .

这玩意儿不应该测试得出结论的

[ 本帖最后由 yecheng_110 于 2009-10-14 13:02 编辑 ]
作者: szedwin    时间: 2009-10-13 22:46
是的
作者: szedwin    时间: 2009-10-13 22:59
#!/usr/bin/perl

@people=qw{fred betty barney dino Wilma pebbles bamm-bamm};


foreach $item (@people)
{
        printf("%d -> $item\n", $i++);
}


# ./test1.pl
0 -> fred
1 -> betty
2 -> barney
3 -> dino
4 -> Wilma
5 -> pebbles
6 -> bamm-bamm




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2