perl中的控制语句及函数定义

来源:互联网 发布:剑网三捏脸数据是视频 编辑:程序博客网 时间:2024/06/09 17:33

1. 条件控制语句

if(条件表达式)

{

#语句

}

else

{

#语句

}

given…when结构形式为:

given (标量)

when()  { }

when()  { }

when()  { }

when()  { }

 

given语句的用法为:

#!/usr/bin/perl -wuse 5.010001;my $m=<STDIN>;given ($m){when (/[0-9]/) {print "it is a number\n";}when (/[a-z]/)  {print "it is a letter\n"}default  {print "\n";}}
2. 循环控制语句

(1)while (条件表达式)

{

# 循环体语句

}

 (2)until (条件表达式)

{

# 循环体

}

(3)do

{

#循环体

}while(条件表达式)

(4)foreach标量(标量)

{

# 循环体

}

foreach的简单使用实例为:

#!/usr/bin/perl -w

foreach $m (1..10)

{

print "$m\n";

}

 (5)for循环语句与foreach等价

形式为

for(表达式;表达式;表达式)

(6)循环控制的next,last以及redo

next语句用于跳过本次循环,执行下一次循环,last语句用于退出循环,redo语句用于回到本次循环的开始。next与redo 的区别在于next会跳过本次循环。下面是三种语句的使用实例:

#!/usr/bin/perl -wuse 5.01;my $n;for($n=0;$n<10;$n++){say "$n";say "input a command:next,last or redo";my $com=<STDIN>;last if $com=~/last/;next if $com=~/next/;redo if $com=~/redo/;}

在上面的程序中,输入last会跳出循环,输入redo会再次打印本次循环的输出,输入next会打印下一个数字。

(7)上面讲到的last仅仅能退出本层循环,如果想要退出多层循环,可以使用带有标签的语句。使用的例子为:

#!/usr/bin/perl -wuse 5.01;my $num;my $j;LABEL:for($num=0;$num<10;$num++){for($j=0;$j<$num;$j++){say "input a string";my $str=<STDIN>;if ($str=~/stop/){last LABEL;}say "you have input: $str";}}

在for循环的前面加了LABEL标签,在内层循环中使用last LABEL就可以退出两层循环了。上面的程序中输入stop即可退出循环。

3.  函数的定义及使用

函数的基本形式为

sub  <函数名>

{

# 函数体

}

如定义函数

sub hello

{

print “hello world\n”;

}

可以在意表达式中使用子程序名加上&来调用它,

#! /usr/bin/perl –wsub hello{print “hello world\n”;}&hello;

程序中出现hello,world

下面定义了guess函数,用循环语句实现猜数字的功能:

#!/usr/bin/perl -wmy $n=100;my $num=int(rand($n));sub guess{do {print "input a number which is in the range of (0,100)";$number=chmop(<STDIN>);if ($number == $num){print "riht\n";}elsif ($number < $num){print "too low\n";}else {print "too high\n";}}while (1);}&guess;


 

0 0
原创粉丝点击