## 利用內插將字符串嵌入到另一個字符串中
雙引號("")字符串能夠內插其他變量。
~~~
my $name = "Inigo Montoya";
my $relative = "father";
print "My name is $name, you killed my $relative";
~~~
## 非內插字符串
如果你不想要內插,那么使用單引號('')。
~~~
print 'You may have won $1,000,000';
~~~
或者,你也可以轉義特殊字符(印記)。
~~~
print "You may have won \$1,000,000";
~~~
## 在字符串中使用 Email 地址要小心
此 Email 地址并不是你想要的:
~~~
my $email = "andy@foo.com";
print $email;
# Prints "andy.com"
~~~
這里的問題是?_@foo_?作為數組被內插了。如果你打開了?`use warnings`,那么此類問題就很明顯了:
~~~
$ perl foo.pl
Possible unintended interpolation of @foo in string at foo line 1.
andy.com
~~~
解決辦法是,要么使用非內插的引號:
~~~
my $email = 'andy@foo.com';
my $email = q{andy@foo.com};
~~~
要么轉義?_@_:
~~~
my $email = "andy\@foo.com";
~~~
好的著色代碼編輯器將幫助你防止此類問題。
## 使用?`length()`?獲得字符串的長度
~~~
my $str = "Chicago Perl Mongers";
print length( $str ); # 20
~~~
## 使用?`substr()`?提取字符串
`substr()`?能夠做各種字符串提取:
~~~
my $x = "Chicago Perl Mongers";
print substr( $x, 0, 4 ); # Chic
print substr( $x, 13 ); # Mongers
print substr( $x, -4 ); # gers
~~~
## 關于字符串 vs. 數字不必擔心太多
不像其他語言,Perl 不知道字符串來自于數字。它將做最好的 DTRT。
~~~
my $phone = "312-588-2300";
my $exchange = substr( $phone, 4, 3 ); # 588
print sqrt( $exchange ); # 24.2487113059643
~~~
## 利用?`++`?操作符自增非數字字符串
你能夠利用?`++`?來自增字符串。字符串`abc`自增后變成`abd`。
~~~
$ cat foo.pl
$a = 'abc'; $a = $a + 1;
$b = 'abc'; $b += 1;
$c = 'abc'; $c++;
print join ", ", ( $a, $b, $c );
$ perl -l foo.pl
1, 1, abd
~~~
注意:你必須使用?`++`?操作符。在上述示例中,字符串`abc`被轉換成?_0_,然后再自增。
## 利用?`heredocs`?創建長字符串
Heredocs 允許連續文本,直到遇到下一個標記。使用內插,除非標記在單引號內。
~~~
my $page = <<HERE;
<html>
<head><title>$title</title></head>
<body>This is a page.</body>
</html>
HERE
~~~