What is the difference between single and double quotes in Perl?

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

For example, I have two variables as shown below:

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

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

+13
string perl
Jun 03 '09 at 9:14
source share
6 answers

Double quotes use variable expansion. Single quotes are not

In a double-quoted string, you need to avoid certain characters so that they are not interpreted differently. You do not use single quotes (except for the backslash, if this is the trailing character in the string)

 my $var1 = 'Hello'; my $var2 = "$var1"; my $var3 = '$var1'; print $var2; print "\n"; print $var3; print "\n"; 

This will lead to the conclusion

 Hello $var1 

Perl Monks has a pretty good explanation for this here.

+30
Jun 03 '09 at 9:18
source share

'will not allow variables and escape sequences

"will allow variables and escape characters.

If you want to keep your \ character in a string in $ var2, use "\\ ("

+4
Jun 03 '09 at 9:17
source share

Double quotes are interpreted, and a single quote is not

+3
Jun 03 '09 at 9:17
source share

Perl accepts single-quoted strings as is and interpolates double-quoted strings. Interpolate means that it replaces variables with variable values, and also understands escaped characters. So, your "\ (" is interpreted as "(', and your regular expression becomes m / (/, so Perl complains).

+2
Jun 03 '09 at 9:25
source share

If you are going to create regular expression strings, you really should use the qr // quote-like operator :

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

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

 print "$var1\n"; #prints (?-xism:\() 
+2
Jun 03 '09 at 16:07
source share

"" Supports variable interpolation and escaping. therefore, shielding is performed inside "\(" \

Where "not supported". So, '\(' literally \(

+1
Jun 03 '09 at 9:20
source share



All Articles