$number = 11; $text = "This text contains the number $number."; 则$text的内容为:"This text contains the number 11."
.双引号内的字符串中支持转义字符 Table 3.1. Escape sequences in strings. Escape Sequence Description \a Bell (beep) \b Backspace \cn The Ctrl+n character \e Escape \E Ends the effect of \L, \U or \Q \f Form feed \l Forces the next letter into lowercase \L All following letters are lowercase \n Newline \r Carriage return \Q Do not look for special pattern characters \t Tab \u Force next letter into uppercase \U All following letters are uppercase \v Vertical tab \L、\U、\Q功能可以由\E关闭掉,如: $a = "T\LHIS IS A \ESTRING"; # same as "This is a STRING"
.要在字符串中包含双引号或反斜线,则在其前加一个反斜线,反斜线还可以取消变量替换,如:
$res = "A quote \" and A backslash \\"; $result = 14; print ("The value of \$result is $result.\n")的结果为: The value of $result is 14. .可用\nnn(8进制)或\xnn(16进制)来表示ASCII字符,如: $result = "\377"; # this is the character 255,or EOF $result = "\xff"; # this is also 255
.单引号字符串 单引号字符串与双引号字符串有两个区别,一是没有变量替换功能,二是反斜线不支持转义字符,而只在包含单引号和反斜线时起作用。单引号另一个特性是可以跨多行,如: $text = 'This is two lines of text '; 与下句等效: $text = "This is two\nlines of text\n"; .字符串和数值的互相转换 例1: $string = "43"; $number = 28; $result = $string + $number; # $result = 71 若字符串中含有非数字的字符,则从左起至第一个非数字的字符,如: $result = "hello" * 5; # $result = 0 $result = "12a34" +1; # $result = 13 .变量初始值 在PERL中,所有的简单变量都有缺省初始值:"",即空字符。但是建议给所有变量赋初值,否则当程序变得大而复杂后,很容易出现不可预料且很难调试的错误。
Table 3.3. 赋值操作符 操作符 描述 = Assignment only += Addition and assignment -= Subtraction and assignment *= Multiplication and assignment /= Division and assignment %= Remainder and assignment **= Exponentiation and assignment &= Bitwise AND and assignment |= Bitwise OR and assignment ^= Bitwise XOR and assignment Table 3.4. 赋值操作符例子