while 控制结构:
perl和大部分用来实现算法的语言一样,也有好几种循环结构,在while循环中,只要条件待续为
真,就会不断执行块里的程序代码:
$count = 0; while ($count <20) { $count += 2; ### eq $count = $count +2 ; print "count is now $count\n"; }
|
这里的真假值与之前提到的if条件测试里的真假值定义相同。
undef值:
如果还没赋值就用到了某个标量,会有什么结果呢?答案是,不会发生什么大不了的事,也绝对不
会让程序中止运行。在首次被赋值之前,变量的初始值就是特殊的undef(未定义),它在Perl里
的意思只不过是:这里空无一物,走开,走开。如果你想把这个“空无一物”当成数字,使用,它就
会假设这是0,如果当成字符串使用,它就会假设这是空字符串。但是undef既不是数字也不是字符
串,它完全是另一种类型的标量值。
既然undef作为数字时会视为零,我们可以很容易地构成一个数值累加器,它在开始时是空的:
#累加一些奇数
$n = 1; while ($n < 10) { $sum += $n; $n +=2; #准备下一个奇数
} print "The total was $sum.\n";
|
defined 函数:
“行输入”操作符有时候会返回undef。在一般状况下,它会返回一行文字,但若没有更多输
入,比如读到文件结尾(end-of-file),它就会返回undef来表示这个状况,要判断某个字符串是
undef而不是空字符串,可以使用defined函数,如果是undef,该函数返回假,否则返回真。
$madonna = <STDIN>; if (defined($madonna)) { print "The input was $madonna"; } else { print "No input available!\n"; }
习题: ================================== #!/usr/bin/perl -w
$pi = 3.141592654; $circ = 2 * $pi * 12.5; print "The circumference of a circle of radius 12.5 is $circ.\n"; ==================================
#!/usr/bin/perl -w
$pi = 3.141592654; print "What is the radius?"; chomp($radius = <STDIN>); $circ = 2 * $pi * $radius; print "The circumference of a circle of radius $radius is $circ.\n";
=====================================================================
#!/usr/bin/perl -w
$pi = 3.141592654; print "What is the radius?"; chomp($radius = <STDIN>); $circ = 2 * $pi * $radius; if ($radius < 0 ) { $circ = 0; } print "The circumference of a circle of radius $radius is $circ.\n";
=====================================================================
$pi = 3.141592654; $radius = <STDIN>; chomp ($radius); if ( $radius < 0 ) { print "The circumference of a circle of radius $radius is 0.\n"; } else { $circ = 2 * $pi * $radius; print "The circumference of a circle of radius $radius is $circ.\n"; }
======================================================================
#!/usr/bin/perl -w
print "Enter first number: "; chomp($one = <STDIN>); print "Enter second number: "; chomp($two = <STDIN>); $result = $one * $two; print "The result is $result.\n";
=======================================================================
print "Enter a string: "; $str = <STDIN>; print "Enter a number of times: "; chomp ($num = <STDIN>); $result = $str x $num; print "The result is:\n$result";
|
13:13 2010-8-15
阅读(614) | 评论(0) | 转发(0) |