Perl Quotes and Escape Sequences

Perl string literals are enclosed in quotation marks. You can use either single quotes ('') or double quotes ("").

print "hello";
print 'hello'; 

Now suppose you need to print a string which contains a single or double quote such as following strings:

This is bob's watch.
Alice replied, "It was a birthday gift."

If I do the following,

print 'This is Bob's watch.';
Alice replied, "It was a birthday gift." 

Then I would get an error message stating that the "substitution pattern was not terminated". This error is generated because Perl would read the following string: 'This is Bob'. Then it would not know what to do with "s watch.'".

There are several ways to resolve this problem.

Alternating quotes The simplest technique is to alternate the quotes.

print "This is Bob's watch.";
print 'Alice replied, "It was a birthday gift."'; 

If the string contains a single quote, we use double quotes and if the string contains double quotes, we use single quotes. This technique could not be used if you have both single and double quotes inside a string.

You must also understand the differences between single and double quotes before using this approach. Double quotes support variable interpolation, single quotes do not. Suppose I run the following program:

#!/usr/bin/perl
$name = "John";
print 'His name is $name\n";
print "His name is $name\n";

This program would print the following results:

His name is $name
His name is John 

Adding Backslashes Another simple technique is to add backslashes before the quotes inside the string.

print 'This is Bob\'s watch.'; print "Alice replied, \"It was a birthday gift\""; 

With this technique, you can escape both single and double quotes inside a string. However, there are times when you would find this technique very hectic. For example, when there are 30 quotes to escape which is quite common when you are printing HTML.

q and qq operators The q operator escapes single quotes and the qq operator escapes double quotes. These operators are used as follows:

q(This is Bob's watch.); qq(Alice replied, "It was a birthday gift"); 

The escaped sequence is to be placed between the parentheses. You can also use any of the following escape sequences:

< >, or [ ] 

Most programmers tend to use backslashes, q, and qq operators. There are several other advanced techniques as well. The best solution, however, is always the one which best suits your needs.

Technologies: 
Actions: