While we're here, let's look at the assignments above. You'll see that some have double quotes, some have single quotes, and some have no quotes at all.
In Perl, quotes are required to distinguish strings from the language's reserved words or other expressions. Either type of quote can be used, but there is one important difference: double quotes can include other variable names inside them, and those variables will then be interpolated - as in the last example above - while single quotes do not interpolate.
# single quotes don't interpolate... my $price = '$9.95'; # double quotes interpolate... my $invoice_item = "24 widgets at $price each\n"; print $invoice_item; |
The above example is available in your directory as exercises/interpolate.pl so you can experiment with different kinds of quotes.
Note that special characters such as the \n newline character are only available within double quotes. Single quotes will fail to expand these special characters just as they fail to expand variable names.
When using either type of quotes, you must have a matching pair of opening and closing quotes. If you want to include a quote mark in the actual quoted text, you can escape it by preceding it with a backslash:
print "He said, \"Hello!\"\n"; |
You can also use a backslash to escape other special characters such as dollar signs within double quotes:
print "The price is \$300\n"; |
To include a literal backslash in a double-quoted string, use two backslashes: \\
There are special quotes for executing a string as a shell command (see "Input operators" on page 52 of the Camel), and also special quoting functions (see "Pick your own quotes" on page 41).
Write a script which sets some variables:
your name
your street number
your favourite colour
Print out the values of these variables using double quotes for variable interpolation
Change the quotes to single quotes. What happens?
Write a script which prints out C:\WINDOWS\SYSTEM\ twice -- once using double quotes, once using single quotes. How do you have to escape the backslashes in each case?
You'll find answers to the above in exercises/answers/scalars.pl.