string Perl 中的单引号和双引号有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/943795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:27:05  来源:igfitidea点击:

What's the difference between single and double quotes in Perl?

perlstring

提问by chappar

In Perl, what is the difference between 'and "?

在 Perl 中,'和之间有什么区别"

For example, I have 2 variables like below:

例如,我有 2 个变量,如下所示:

$var1 = '\(';
$var2 = "\(";

$res1 = ($matchStr =~ m/$var1/);
$res2 = ($matchStr =~ m/$var2/);

The $res2statement complains that Unmatched ( before HERE mark in regex m.

$res2声明中抱怨说Unmatched ( before HERE mark in regex m

回答by Xetius

Double quotes use variable expansion. Single quotes don't

双引号使用变量扩展。单引号不

In a double quoted string you need to escape certain characters to stop them being interpreted differently. In a single quoted string you don't (except for a backslash if it is the final character in the string)

在双引号字符串中,您需要对某些字符进行转义以阻止它们被不同地解释。在单引号字符串中你没有(反斜杠除外,如果它是字符串中的最后一个字符)

my $var1 = 'Hello';

my $var2 = "$var1";
my $var3 = '$var1';

print $var2;
print "\n";
print $var3;
print "\n";

This will output

这将输出

Hello
$var1

Perl Monks has a pretty good explanation of this here

Perl Monks 对此有很好的解释here

回答by Chaos

' will not resolve variables and escapes

' 不会解析变量和转义

" will resolve variables, and escape characters.

" 将解析变量,并转义字符。

If you want to store your \ character in the string in $var2, use "\\("

如果要将 \ 字符存储在 $var2 的字符串中,请使用 "\\("

回答by Silfverstrom

Double quotation marks interpret, and single quotation do not

双引号解释,单引号不解释

回答by Igor Krivokon

Perl takes the single-quoted strings 'as is' and interpolates the double-quoted strings. Interpolate means, that it substitutes variables with variable values, and also understands escaped characters. So, your "\(" is interpreted as '(', and your regexp becomes m/(/, this is why Perl complains.

Perl 接受单引号字符串“原样”并插入双引号字符串。插值意味着,它用变量值替换变量,并且还理解转义字符。所以,你的 "\(" 被解释为 '(',你的正则表达式变成了 m/(/,这就是 Perl 抱怨的原因。

回答by Chas. Owens

If you are going to create regex strings you should really be using the qr// quote-like operator:

如果您要创建正则表达式字符串,您真的应该使用qr// 类似引号的运算符

my $matchStr = "(";
my $var1 = qr/\(/;
my $res1 = ($matchStr =~ m/$var1/);

It creates a compiled regex that is much faster than just using a variable containing string. It also will return a string if not used in a regex context, so you can say things like

它创建了一个编译的正则表达式,它比仅使用包含字符串的变量快得多。如果不在正则表达式上下文中使用,它也会返回一个字符串,因此您可以这样说

print "$var1\n"; #prints (?-xism:\()

回答by Canopus

"" Supports variable interpolation and escaping. so inside "\("\escapes (

"" 支持变量插值和转义。所以里面"\("\逃逸(

Where as ' ' does not support either. So '\('is literally \(

其中 ' ' 也不支持。'\('从字面上看也是如此\(