Perl初级教程 | |
|
|
第三页:标量 Perl中最基本的变量是标量。标量可以是字符串或数字,而且字符串和数字可以互换。例如,语句 $priority = 9; 设置标量$priority为9,但是也可以设置它为字符串: $priority = 'high'; Perl也接受以字符串表示的数字,如下: $priority = '9'; $default = '0009'; 而且可以接受算术和其它操作。 一般来说,变量由数字、字母和下划线组成,但是不能以数字开始,而且$_是一个特殊变量,我们以后会提到。同时,Perl是大小写敏感的,所以$a和$A是不同的变量。 操作符和赋值语句: Perl使用所有的C常用的操作符: $a = 1 + 2; # Add 1 and 2 and store in $a $a = 3 - 4; # Subtract 4 from 3 and store in $a $a = 5 * 6; # Multiply 5 and 6 $a = 7 / 8; # Divide 7 by 8 to give 0.875 $a = 9 ** 10; # Nine to the power of 10 $a = 5 % 2; # Remainder of 5 divided by 2 ++$a; # Increment $a and then return it $a++; # Return $a and then increment it --$a; # Decrement $a and then return it $a--; # Return $a and then decrement it 对于字符串,Perl有自己的操作符: $a = $b . $c; # Concatenate $b and $c $a = $b x $c; # $b repeated $c times Perl的赋值语句包括: $a = $b; # Assign $b to $a $a += $b; # Add $b to $a $a -= $b; # Subtract $b from $a $a .= $b; # Append $b onto $a 其它的操作符可以在perlop手册页中找到,在提示符后敲入man perlop。 互操作性: 下面的代码用串联打印apples and pears: $a = 'apples'; $b = 'pears'; print $a.' and '.$b; 最后的打印语句中应该只包含一个字符串,但是: print '$a and $b'; 的结果为$a and $b,不是我们所期望的。 不过我们可以用双引号代替单引号: print "$a and $b"; 双引号强迫任何代码的互操作,其它可以互操作的代码包括特殊符号如换行(\n)和制表符(\t)。>> Perl初级教程
|
|