什麼是 Perl 字串字面量?


字串是字元序列。它們通常是由單引號(')或雙引號(")分隔的字母數字值。它們的工作方式與UNIX shell引號非常相似,您可以使用單引號字串和雙引號字串。

雙引號字串字面量允許變數插值,而單引號字串不允許。某些字元在前面帶有反斜槓時具有特殊含義,它們用於表示換行符(\n)或製表符(\t)等。

您可以直接在雙引號字串中嵌入換行符或以下任何轉義序列:

轉義序列含義
\反斜槓
\'單引號
\"雙引號
\a警報或鈴聲
\b退格
\f換頁
\n換行
\r回車
\t水平製表符
\v垂直製表符
\0nn建立八進位制格式的數字
\xnn建立十六進位制格式的數字
\cX控制字元,x可以是任何字元
\u強制下一個字元大寫
\l強制下一個字元小寫
\U強制所有後續字元大寫
\L強制所有後續字元小寫
\Q反斜槓所有後續非字母數字字元
\E結束 \U、\L 或 \Q

示例

讓我們再次看看字串在單引號和雙引號下的行為。在這裡,我們將使用上表中提到的字串轉義符,並將使用標量變數來賦值字串值。

 線上演示

#!/usr/bin/perl
# This is case of interpolation.
$str = "Welcome to \ntutorialspoint.com!";
print "$str\n";

# This is case of non-interpolation.
$str = 'Welcome to \ntutorialspoint.com!';
print "$str\n";

# Only W will become upper case.
$str = "\uwelcome to tutorialspoint.com!";
print "$str\n";

# Whole line will become capital.
$str = "\UWelcome to tutorialspoint.com!";
print "$str\n";

# A portion of line will become capital.
$str = "Welcome to \Ututorialspoint\E.com!";
print "$str\n";

# Backsalash non alpha-numeric including spaces.
$str = "\QWelcome to tutorialspoint's family";
print "$str\n";

輸出

這將產生以下結果:

Welcome to
tutorialspoint.com!
Welcome to \ntutorialspoint.com!
Welcome to tutorialspoint.com!
WELCOME TO TUTORIALSPOINT.COM!
Welcome to TUTORIALSPOINT.com!
Welcome\ to\ tutorialspoint\'s\ family

更新於:2019-11-28

670 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.