Chinaunix首页 | 论坛 | 博客
  • 博客访问: 528467
  • 博文数量: 55
  • 博客积分: 1520
  • 博客等级: 上尉
  • 技术积分: 661
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-19 22:01
文章存档

2013年(1)

2012年(1)

2011年(7)

2010年(16)

2009年(30)

我的朋友

分类:

2009-05-25 18:08:37

一.条件判断
        if ( )
        {
               
        }
        elsif ( )
        {
               
        }
        ...
        else
        {
               
        }


二.循环
1.while循环
        while ( )
        {
               
        }

2.until循环
        until ( )
        {
               
        }

3.类C的for循环
        for ($count=1; $count <= 5; $count++)
        {
                #statements inside the loop go here
        }

4.针对列表(数组)每个元素的foreach循环
        foreach localvar (listexpr)
        {
                statement_block;
        }
        注:
                (1)此处的循环变量localvar是个局部变量,如果在此之前它已有值,则循环后仍恢复该值.
                (2)在循环中改变局部变量,相应的数组变量也会改变.
        例:
        foreach $word (@words)
        {
                if ($word eq "the")
                {
                        print ("found the word 'the'\n");
                }
        }
        此外,如果localvar省略了的话,PERL将使用默认变量$_.
        例:
        @array = (123, 456, 789);
        foreach (@array)
        {
                print $_;
        }
        $_是PERL最常使用的默认变量,上例中print后面的$_也可以去掉,当print没有参数时,会默认输出$_变量.

5.do循环
        do
        {
                statement_block
        } while_or_until(condexpr);
        do循环至少执行一次循环.

6.循环控制
        退出循环为last,与C中的break作用相同;
        执行下一个循环为next,与C中的continue作用相同;
        PERL特有的一个命令是redo,其含义是重复此次循环,即循环变量不变,回到循环起始点.但要注意,redo命令在do循环中不起作用.

三.单行条件
        语法为statement keyword condexpr.其中keyword可为if, unless, while或until.例如:
                print ("This is zero.\n") if ($var == 0);
                print ("This is zero.\n") unless ($var != 0);
                print ("Not zero yet.\n") while ($var-- > 0);
                print ("Not zero yet.\n") until ($var-- == 0);
  虽然条件判断写在后面,但却是先执行的。

阅读(1147) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~