Home > Back-end >  Is there a difference betwen qq(<text>) and "<text>" in Perl?
Is there a difference betwen qq(<text>) and "<text>" in Perl?

Time:12-23

In perl you can use both qq(<text>) and "<text>" to create double quoted text. Is there any difference between the two?

(Same question for q(<text>) and '<text>')

CodePudding user response:

No.

"<text>" is short for qq"<text>".

'<text>' is short for q'<text>'.

Quote-Like Operators

CodePudding user response:

In addition to them being identical, there is the point that you can use q() qq() with different delimiters (like you can with many Perl operators) to make quoting simpler. For example qq#The movie "Foo"#, q{Some other 'Foo'}. Compare

"Bob said, \"What's that?\""      'Bob said, "What\'s that?"'   qq(Bob said, "What's that?")
"Kim whispers, \"(...)\""         qq|Kim whispers, "(...)"|
s/http:\/\/www.example.com\//http:\/\/www.example.net\//  # "leaning toothpick syndrome" (1)
s#http://www.example.com/#http://www.example.net/#        # fixed

(1): leaning toothpick syndrome

CodePudding user response:

Deparse Perl programs to see how Perl interpreted you wrote. When you use the generalized quotes, you get back the single and double quotes:

$ perl -MO=Deparse -e '$s = q(abc)'
$s = 'abc';
-e syntax OK

$ perl -MO=Deparse -e '$s = qq/ab "c" d/'
$s = 'ab "c" d';
-e syntax OK

$ perl -MO=Deparse -e '$s = qq(abc$$)'
$s = "abc${$}";
-e syntax OK

Besides using these to allow the ' and " to appear in the string, I find them very handy for one liners so that the ' and " don't trigger shell problems:

% perl -le "print qq(PID is $$)"
  •  Tags:  
  • perl
  • Related