免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 6482 | 回复: 4
打印 上一主题 下一主题

while循环条件的一个疑问(已经明白) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-09-19 14:10 |只看该作者 |倒序浏览
本帖最后由 gaochong 于 2010-09-19 14:45 编辑

自己应该也算是perl入门的人了,但看到一个while循环条件后搞不明白,请各位指点。

如下子例程中的while循环条件中   $n=$n-1  怎么理解?

sub mask {
        my $n=shift;
        my $j;
        while ($n=$n-1) {
                $j++;
        }
        return $j;
}

print mask(2);

论坛徽章:
0
2 [报告]
发表于 2010-09-19 14:26 |只看该作者
本帖最后由 justagain 于 2010-09-19 14:35 编辑

回复 1# gaochong

共同学习一下,我的理解是
sub mask {
        my $n=shift;
        my $j;
        while ($n=$n-1) {   #这里因为$n=$n-1始终为真,$n开始递减,while一直会运行下去,一直到$n-1之后变成0。
                $j++;               #$j值会不断加1
        }
        return $j;                # 返回最终的$j值
}

print mask(2);               #当指定了值为2后, n开始从2递减,运行一次后,j值为1;第二次停住运行。直接返回$j值,为1

整个程序可以看成是在$n递减的同时,将$j进行递增的操作。

不知道我的理解是否正确。

求职 : 技术支持/维
论坛徽章:
0
3 [报告]
发表于 2010-09-19 14:32 |只看该作者
提示: 作者被禁止或删除 内容自动屏蔽

论坛徽章:
0
4 [报告]
发表于 2010-09-19 14:44 |只看该作者
2.6.1. Boolean Values
You may use any scalar value as the conditional of the if control structure. That's handy if you want to store a true or false value into a variable, like this:

    $is_bigger = $name gt 'fred';
    if ($is_bigger) { ... }



But how does Perl decide whether a given value is true or false? Perl doesn't have a separate Boolean data type as some languages have. Instead, it uses a few simple rules:[*]

[*] These aren't the rules Perl uses but are rules you can use to get the same result.

If the value is a number, 0 means false; all other numbers mean true.

If the value is a string, the empty string ('') means false; all other strings mean true.

If the value is another kind of scalar than a number or a string, convert it to a number or a string and try again.[]

[] This means that undef (which we'll see soon) means false, and all references (which are covered in the Alpaca book) are true.

There's one trick hidden in those rules. Because the string '0' is the same scalar value as the number 0, Perl has to treat them the same. That means that the string '0' is the only nonempty string that is false.

If you need to get the opposite of any Boolean value, use the unary not operator, !. If what follows it is a true value, it returns false; if what follows is false, it returns true:

    if (! $is_bigger) {
      # Do something when $is_bigger is not true
    }

论坛徽章:
0
5 [报告]
发表于 2010-09-19 15:01 |只看该作者
本帖最后由 珞水的大叔 于 2010-09-19 15:03 编辑
  1. while ($n=$n-1) {
  2.     $j++;
  3. }
复制代码
等于
  1. $n=$n-1;
  2. while ($n != 0) {
  3.     $j++;
  4.     $n=$n-1;
  5. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP