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

后端 未结 6 1265
小蘑菇
小蘑菇 2020-11-30 13:50

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

For example, I have 2 variables like below:

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


        
相关标签:
6条回答
  • 2020-11-30 14:17

    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.

    0 讨论(0)
  • 2020-11-30 14:19

    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

    0 讨论(0)
  • 2020-11-30 14:27

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

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

    0 讨论(0)
  • 2020-11-30 14:28

    ' 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 "\\("

    0 讨论(0)
  • 2020-11-30 14:29

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

    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:\()
    
    0 讨论(0)
  • 2020-11-30 14:30

    Double quotation marks interpret, and single quotation do not

    0 讨论(0)
提交回复
热议问题