Quoting in Perl

[ Perl tips index ]
[ Subscribe to Perl tips ]

This tip will discuss the structures Perl provides to make quoting easier. These are typically called ``roll-your-own'' quotes or quote-like operators.

We've all seen (and probably written) code which suffers from quoting problems. Some examples are below.

        print 'Albert\'s surname is Alberna' . "\n";

        print "Bettie said \"It's no good crying over split milk.\"\n";

        print 'The field name was "' . $fieldname . '"' . "\n";

        my @friends = ("Albert", "Bettie", "Caroline", "Denis", "Eugene");

In the first case, we can fix the problem by just using double quotes instead of single quotes.

        print "Albert's surname is Alberna\n";

Perhaps the second case would be better in single quotes?

        print 'Bettie said "It\'s no good crying over split milk."' . "\n";

(Shame about that newline). In the third example we're trying to enclose the fieldname in double quotes. We can't really change our quotes to make it any more clear than it is. Let's try anyway:

        print "The field name was \"$fieldname\"\n";

No great improvements there.

What's wrong with the final example? Nothing really. You can use double quotes, single quotes, or a mixture when creating a list. You just have to make sure that you don't leave any out. It's also a lot of extra typing than should be required, fortunately Perl makes this easier as well.

qq and q

To avoid the problems discussed in the introduction, Perl allows us to pick our own quoting characters when we need to. We can do this by using qq for double quoted strings and and q for single quoted strings. Thus we can write:

        print qq{Albert's surname is Alberna\n};

        print qq/Bettie said "It's no good crying over split milk."\n/;

        print qq<The field name was "$fieldname"\n>;

        # or

        print q[Albert's surname is Alberna], "\n";

        print q!Bettie said "It's no good crying over split milk."!, "\n";

You'll notice that I use a variety of punctuation with each of these operators. Perl allows you to use any punctuation character at all and those which look like they should match up (such as brackets, braces, and parentheses) do. This allows you to pick characters that don't appear in your string.

In addition, if you are using a matching style of delimiters (brackets, braces and parentheses) then those delimiters can appear in your text so long as they're balanced. Thus all of the following also work:

        q< <<(({{['"']}}))>> >;
        q[ <<(({{['"']}}))>> ];
        q{ <<(({{['"']}}))>> };
        q( <<(({{['"']}}))>> );


So how does Perl let us type less punctuation when we're creating a list? By using the qw (quote words) operator. This tells Perl that each element inside (separated by spaces) is a word which you wish to add to the list. Once again you can pick your punctuation.

        my @friends = qw/Albert Bettie Caroline Denis Eugene/;

This doesn't work for variable names and it doesn't work for cases where you wish to include spaces in your elements, but by and large these cases are more rare than those in which you specify single words. If you do need to specify some names which include spaces you might write:

        my @friends = ("Big A", qw/Bettie Caroline Denis Eugene/);


Backticks in Perl are used for executing system commands via the shell. While there are often security issues with doing so we'll mention qx briefly. (The security issues, alternatives and solutions are covered in our Perl Security course.)

In some fonts; backticks ` can look identical to forward ticks ' (single quotes/apostrophes). Further, even when they look dissimilar, a casual reader of your program may assume that your backticked expression is actually single quoted.

As a result we recommend using qx// instead of backticks. qx stands for quote executable and is functionally identical, but visually distinctive. Depending on you system, you can then change:

        my $result = `notepad`;

        # to

        my $result = qx/notepad/;


We mentioned qr briefly a few tips back. qr stands for quote regular expression and allows us to generate regular expressions which are compiled at the same time as the rest of the program rather than when they are first encountered by Perl. It also gives us access to scalar handles for those regular expressions which we can then pass through to subroutines.

        my $regex = qr/Perl Training Australia/;

        if($string =~ /$regex/) {
                print "Yup, that mentions us\n";

Interpolating and non-interpolating strings

What's the difference between using single quotes and double quotes in Perl?
With a static string: nothing. With a string which contains variables and/or escape sequences: lots.

Single quoted strings in Perl don't interpolate. This means that these strings are examples of ``what you see is what you get''. If you include a variable name inside a single quoted string then it will print out that variable name, not the variable contents. If you include an escape sequence, such as \n to generate a newline, then Perl will treat that as a backslash followed by an n, not as a newline.

Double quotes in Perl do interpolate. This means that you can include variables inside these strings and when you do, Perl will use the contents of the variable, rather than its name. Escape sequences also work.

        my $number = 10;
        print "Give me $number pushups\n";

prints Give me 10 pushups and a newline.

There are two exceptions for single quotes ignoring escape characters. If you wish to include an apostrophe in a single quoted string you can precede it with a backlash: \'. This tells Perl that you don't mean to end the string here. A backslash followed by a backslash (\\) tells Perl that you want this backslash to be treated only as a backslash (even if the second backslash immediately preceeds a single quote).

But what about speed?

Perl is very, very good at processing strings. Thus there is no easily discernable time difference between using double quotes or single quotes around a static string, even if you're using a lot of them.

        # These are equally fast
        print "This is a simple static string";
        print 'This is a simple static string';

[ Perl tips index ]
[ Subscribe to Perl tips ]

This Perl tip and associated text is copyright Perl Training Australia. You may freely distribute this text so long as it is distributed in full with this Copyright noticed attached.

If you have any questions please don't hesitate to contact us:

Email: contact@perltraining.com.au
Phone: 03 9354 6001 (Australia)
International: +61 3 9354 6001

Valid XHTML 1.0 Valid CSS