Interpolation in Perl
This page shows how variable interpolation works in Perl. Interpolation, meaning “introducing or inserting something”, is the name given to replacing a variable with the value of that variable.
Interpolated string
In Perl, any string that is built with double quotes (or something meaning double quotes) will be interpolated. That is, any variable or escaped char that appears within the string will be replaced with the value of that variable. Here is a small example:
This would have the following output:
In perl, when you print an array inside double quotes, the array elements are printed with spaces between. The following program provides a small example:
This program produces the following output:
This is very helpful when debugging.
The function qq() works just like double quotes, but makes it easy to put double quotes in your string:
This would produce:
Here documents work in exactly the same way. If the end token of the here document (e.g. <<“EOT”) is surrounded in double quotes, then variables in the here document will be interpolated:
The output of this program is:
Non-interpolated string
Single quoted strings do not interpolate variables or most escaped values, such as \n, (however \’ is the exception). Single quotes are helpful when you want to include a $ or a % or any other special character in your output:
This would produce the output you would want:
The function q() works the same as single quotes, except it makes it easier to include a single quote in your data:
This would produce:
In the same way, variables in here documents, where the end token is surrounded with single quotes, are not interpolated:
This would produce:
Hash keys
When defining a hash, the key of the hash is a string. For example:
The key (on the left) does not have to be quoted unless it contains spaces, or characters that may be interpolated. For example, the above hash could be written as:
But neither of the following keys are valid:
When to use what?
If you are constructing or printing a string that contains no variables, then use single quotes or q(). This makes your code easier to read if there are dollar signs or other special characters in your text.
If you are printing a lot of data use a here document. It will make your code easier to read.
If you need to print a variable amongst some text, use double quotes or qq(). This is much tidier than repeated uses of the ‘.’ concatenation operator.
Sometimes you will find that you do need to use either backslashes or concatenation operators. For example, if you want to print a dollar sign and then an amount in a variable, you could use either:
or:
The first example is probably the better one to use as $$ is the perl variable for process id.