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