Chinaunix首页 | 论坛 | 博客
  • 博客访问: 851557
  • 博文数量: 253
  • 博客积分: 6891
  • 博客等级: 准将
  • 技术积分: 2502
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-03 11:01
文章分类

全部博文(253)

文章存档

2016年(4)

2013年(3)

2012年(32)

2011年(184)

2010年(30)

分类: Python/Ruby

2011-10-10 17:22:30

It turns out that, inside the Perl parser, the keyword foreach is exactly equivalent to
the keyword for. That is, any time Perl sees one of them, it’s the same as if you had typed the other. Perl can tell which you meant by looking inside the parentheses. If
you’ve got the two semicolons, it’s a computed for loop (like we’ve just been talking
about). If you don’t have the semicolons, it’s really a foreach loop:
for (1..10) {  # Really a foreach loop from 1 to 10
  print "I can count to $_!\n";
}
That’s really a  foreach loop, but it’s written  for. Except for that one example, all
through this book, we’ll spell out foreach wherever it appears. But in the real world,
do you think that Perl folks will type those extra four letters?* Excepting only beginners’
code, it’s always written for, and you’ll have to do as Perl does and look for the semi-
colons to tell which kind of loop it is.
In Perl, the true foreach loop is almost always a better choice. In the  foreach loop
(written for) in that previous example, it’s easy to see at a glance that the loop will go
from 1 to 10. But do you see what’s wrong with this computed loop that’s trying to do
the same thing? Don’t peek at the answer in the footnote until you think you’ve found
what’s wrong:†
for ($i = 1; $i < 10; $i++) {  # Oops! Something is wrong here!
  print "I can count to $_!\n";
}
阅读(344) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~