什么是 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.