C风格的循环与Perl循环(在Perl中) [英] C-style loops vs Perl loops (in Perl)

查看:141
本文介绍了C风格的循环与Perl循环(在Perl中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得有一些我没有得到关于Perl的循环机制。



据我了解,

  






$ p

在功能上等价于:

  for(my $ i = 0; $ i <= $#arr; $ i ++){..} 

但是,在我的代码中,它们的运行方式似乎有一些细微的差别。特别是他们决定何时终止的时间。例如:

假定@arr是用一个变量初始化的。



这两个块应该做同样的事情吗?

  for我的$我(0 .. $#ARR)
{
如果(一些条件恰好是真的)
{
push(@arr,$ value);











$ b ($ my $ i = 0; $ i< = $#arr; $ i ++)
{
if(某些条件碰巧是true)
{
push(@arr,$ value);






然而,即使一个新的值被推送在这两种情况下,第一个循环只会在一次迭代后停止。



这是否应该发生?如果是的话为什么

编辑:谢谢你所有的答案,我知道我可以用其他循环机制完成同样的事情。当我问是否还有另一种语法时,我正在专门讨论使用for。显然没有。作为语法来做我想要的是已经实现了C风格。我只是问,因为我被告知避免c风格,但我仍然喜欢我的循环。

解决方案

$ i <= $#arr (0.. $#arr)在任何循环之前都会被计算一次。

同样,第一个代码不会看到对 @arr 尺寸的更改。


I feel like there is something I don't get about perl's looping mechanism.

It was my understanding that

for my $j (0 .. $#arr){...} 

was functionally equivalent to:

for(my $i=0; $i<=$#arr; $i++){..}

However, in my code there seems to be some slight differences in the way they operate. specifically, the time in which they decide when to terminate. for example:

assume @arr is initialized with one variable in it.

These two blocks should do the same thing right?

for my $i (0 .. $#arr)
{
    if(some condition that happens to be true)
    {
        push(@arr, $value);
    } 
} 

and

for (my $i=0; $i<=$#arr; $i++)
{
    if(some condition that happens to be true)
    {
        push(@arr, $value);
    } 
} 

In execution however, even though a new value gets pushed in both cases, the first loop will stop after only one iteration.

Is this supposed to happen? if so why?

EDIT: Thank you for all of your answers, I am aware I can accomplish the same thing with other looping mechanisms. when I asked if there was a another syntax, I was specifically talking about using for. Obviously there isn't. as the syntax to do what I want is already achieved with the c style. I was only asking because I was told to avoid the c style but i still like my for loops.

解决方案

$i<=$#arr is evaluated before each loop while (0 .. $#arr) is evaluated once before any loop.

As such, the first code doesn't "see" the changes to the @arr size.

这篇关于C风格的循环与Perl循环(在Perl中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆