Perl开发的学习-3

发布时间:2019-06-26 09:39:11编辑:auto阅读(1194)

    计算机作为一种计算工具,其优势在于执行重复任务和根据条件进行大量判断(因此循环语句,条件语句及顺序执行语句是计算机控制结构中基本语句,而与人类语言中句法完全不同)。

    clip_image002

    clip_image004

    clip_image006

    clip_image008

    clip_image010

    clip_image012

    clip_image014

    clip_image016

    clip_image018

    clip_image020

    clip_image022

    clip_image024

    [root@windriver-machine test]# cat ctl.pl
    #!/usr/bin/perl

    print "\$a's value restore after the cycle:";
    $a=1;
    print "$a\n";
    foreach $a(2,3,4)
    {
    print "$a is in cycle\n";
    }
    print "$a not in cycle\n";

    print "\n change the var of cycles will impact the data of arrays:\n";
    @a=(1,2,3);
    print "@a\n";

    foreach $c(@a){$c=4 if $c==2;}

    print "@a\n";

    print "\n may visit part elements of arrays:\n";
    @a=(1,2,3);
    print "@a\n";
    foreach $c(@a[1,2]){print "$c\n";}

    print "\n the defalut var of cycles is \$_:\n";
    @a=(1,2,3);
    foreach (@a){print "$_\n";}

    print "\nfor and foreach is same:\n";
    foreach($i=1;$i<5;$i++){print "$i\n";}

    print "using LABEL:\n";
    LABEL:for($i=1;$i<5;$i++){
             for($j=1;$j<5;$j++){
                 print "$i ";
                 last LABEL if $i==3;
              }
            }
    print "\$i=$i\n";

    print "continue test\n";
    $a=0;

    while($a++<10)
    {
    ($f=1,next) if $a==5;
    print "$a";
    }
    continue {
    (print (":$a in continue:"),$f=0) if ($f==1);
    }
    [root@windriver-machine test]# perl ctl.pl
    $a's value restore after the cycle:1
    2 is in cycle
    3 is in cycle
    4 is in cycle
    1 not in cycle

    change the var of cycles will impact the data of arrays:
    1 2 3
    1 4 3

    may visit part elements of arrays:
    1 2 3
    2
    3

    the defalut var of cycles is $_:
    1
    2
    3

    for and foreach is same:
    1
    2
    3
    4
    using LABEL:
    1 1 1 1 2 2 2 2 3 $i=3
    continue test
    1234:5 in continue:678910[root@windriver-machine test]#

    Perl语句根标准C/C++有很大的不一样,需要特别注意。

    1) 条件语句,使用if(){} elsif(){} …else{},需要注意这里是elsif ,另外可以使用unless() {}

    单选if 语句也是只有perl才有,() if() 或者() unless()

    2) 循环条件语句,使用while(){} 或者do{} while() 及while() {} continue{}。 Until(){} ,do{} until(),util(){}continue{},特别是带continue,这一点与C完全不一样,需要特别注意.单选语句,一定要有结束条件。

    3) 循环语句,使用for,foreach.注意这里面的控制last,next,redo,goto跟通常意义的理解也不一样的,需要特别注意。

关键字