Affordable Web Hosting with Excellent Customer Support internet connection free month hosting

Perl Quoting Syntax and Variable Interpolation

When you have a variable that contains something you want to use, in these examples print, you may find yourself combining text with your variable data. Take a look at the following examples:

$name= 'Dave';
print 'My name is $var'; # will print My name is $var
print "My name is $var"; # will print My name is Dave
print 'My name is ' . $var; # will print My name is Dave
print qq{My name is $var}; # will print My name is Dave
print qq|My name is $var|; # will print My name is Dave

What is the difference between these quoting methods? The first print example, using single quotes, means that we do not expand (use variable interpolation or variable expansion) in what we print. In all the other examples we do.
What use is this information?

Take a situation where you are printing html to a browser, and your code contains some css data:

print "Content-type: text/html\n\n
<html>
<head>
<title>This is the title</title>
<style>
.myclass {color:#f00}
</style>
</head>
<body>
<p class="myclass">This is text</p>
</body>
</html>"; # wrong

What happens here is we get an error because you are not escaping the double quotes "".
Also, we are not escaping the brackets in the inline style definition for .myclass.
We could escape the brackets, .myclass\{color:#f00\} and that would solve the problem. But what if you have a hundred brackets? Then your code would no longer resemble html, which you may wish it to.

Using one of these different quotting methods, we can keep our print statement the same without using escaping brackets and double quotes:

print qq|Content-type: text/html\n\n
<html>
<head>
<title>This is the title</title>
<style>
.myclass {color:#f00}
</style>
</head>
<body>
<p class="myclass">This is text</p>
</body>
</html>|; # right