Perl Basic - Conditions
在Perl中,布尔值True和False用字符串来表示,因为所有Scalar类型都可以转换为字符串😑。
其中,False可以是空字符串'', 或者字符串'0'. 其余任何字符串都是True, 包括'00', '0E0'等转换为数值类型等于0的字符串。
一般函数要返回False的时候返回''或undef (undef转换为空字符串'').
逻辑运算符
Perl的逻辑运算符和其他符号和字符都可以使用。
symbolic | textual |
因为程序是顺序执行的,和数学中的逻辑运算有点不一样。程序会先执行运算符左边的表达式,计算它的真假,然后根据运算符,有必要时再计算运算符右边的表达式。
# 先执行open函数打开文件,如果打开文件成功,返回`True`, |
if 和 unless
和Python的if...elif...else语句没有不同,除了在Perl中使用elsif关键词,而不是elif.
if (<cond>) { ... } |
unless 可以看作 if (not <cond>)的缩写。
语法糖:使用if语句控制前一个表达式的执行。
if ($friendly) { print $greeting } |
练习
Use the function
time()to get the current time (a simple integer
number) into a variablePrint the content of this variable
Print the strings “odd” or “even” depending on the value of this
variable. (Hint: use the modulo operator)Bonus: print human readable date, whenever the number is dividable by 3, 5, or 7
Hint: The function localtime() converts the epoch time into a readable
representation:
print localtime(…) . "\n"; # use concatenation with dot operator |
答案:
#!/usr/bin/perl |
三元运算符
$result = $value % 2 == 0 ? "even" : "odd" |
循环控制:while / until / for / last / next / continue
- While循环
while (<cond>) { |
- do while循环
do { |
使用自定义标签标注循环入口和出口
next默认跳出当前循环,进行下一次循环,类似Python中的continue。next接自定义标签则跳出循环到指定标签处继续执行。last跳出循环,类似Python中的break
FOO: while (<cond>) { |
- for循环
# expr0 example: $i = 0 |
练习
Create a script, that lets the user guess a random number, giving feedback if the guess was small or big.
Hints:
- random integer between 0 and 10:
$value = int rand 10 - a line of user input:
$input = readline;
答案:
#!/usr/bin/perl |
