2.4.2 标量赋值
标量变量最通常的操作是赋值:将值赋给变量。Perl 中的赋值符是等号(和许多语言类似),将等号右边的值赋给等号左边
的变量:
$fred = 17; #将17 赋给变量$fred
$barney =‘hello’; #将五个字母的字符串‘hello’赋给$barney
$barney = $fred + 3;# 将$fred 的值加上三赋给$barney (20)
$barney= $barney*2;#将变量$barney 乘2 再赋给$barney (40)
2.4.3 二元赋值操作符
例如,下面两行是等价的:
$fred = $fred + 5; #没有用二元赋值操作符
$fred+=5; #利用二元赋值操作符
下面的也是等价的:
$barney = $barney*3;
$barney*=3;
2.5 print 输出
print “hello world/n”; #输出hello world,后接换行符
print “The answer is ”;
print 6 * 7;
print “./n”;
也可以将一串值赋给print,利用逗号分开:
print “The answer is ”,6*7, “./n”;
2.5.1 字符串中标量变量的内插
$mean = “brontosaurus steak”;
$barney = “fred ate a $meal”; #$barney 现在是“fred ate a brontosaurus steak”
$barney = ‘fred ate a’. $meal; #同上
2.5.3 比较运算符
表2-3 数字和字符串的比较运算符
比较关系数字字符串
相等= = eq
不等!= ne
小于< Lt
大于> gt
小于或等于<= le
大于或等于>= ge
2.6 if 控制结构
if($name gt ‘fred’)
{
print “‘$name’comes after ‘fred’in sorted order./n”;
}
else
{
print “‘$name’does not come after ‘fred’./n”;
print “Maybe it’s the same string, in fact./n”;
}
2.6.Boolean 值
在if 控制结构的条件判断部分可以使用任意的标量值。这在某些时候将很方便,如:
$is_bigger = $name gt‘fred’;
if($is_bigger){… }
那么,Perl 是怎么判断其值得true 或false 呢?Perl 不同于其它的一些语言,它没有Boolean 类型。它利用如下几条规则◆:
◆事实上Perl 不是用的这些规则,但你可以利用它们方便记忆,其结果是一致的。
● 如果值为数字,0 是false;其余为真
● 如果值为字符串,则空串(‘’)为false;其余为真
● 如果值的类型既不是数字又不是字符串,则将其转换为数字或字符串后再利用上述规则◆。
◆这意味着undef(很快会看到)为false。所有的引用(在Alpaca 书中有详细讨论)都是true。
2.7 用户输入 <STDIN>;
$line = <STDIN>;
if($line eq “/n”){
print “That was just a blank line!/n”;
}else{
print “That line of input was: $line”;
}
2.8 chomp 操作
chomp($text); #去掉换行符(/n)。
2.9 while 控制结构
while ($count < 10) {
$count + = 2;
print “count is now $count/n”; #打印出2 4 6 8 10
}
2.10 undef 值
2.1.1 defined 函数
能返回undef 的操作之一是行输入操作,<STDIN>。通常,它会返回文本中的一行。但如果没有更多的输入,如到了文件
的结尾,则返回undef◆。要分辨其是undef 还是空串,可以使用defined 函数,它将在为undef 时返回false,其余返回true。
◆事实上,从键盘输入,不会有“end-of-file”,但其可重定向到文件中再输入。或者用户可能输入某些键,而系统将其作为end-of-file 看待。
$madonna = <STDIN>;
If ($defined ($madonna)){
print “The input was $madonna”;
}else{
print “No input available!/n”;
}
如果想声明自己的undef 值,可以使用undef:
$madonna = undef ; #同$madonna 从未被初始化一样。