Perl logo

Perl Refreshments ⌘

Quoting Variables

You may be intimidated when we talk about the number of ways a variable can be quoted, but not to worry. Perl is somewhat intelligent.

Here are the ways you can use quotes:

Customary Generic Meaning Interpolates
'' q// Literal string No
"" qq// Literal string Yes
`` qc// Command Execution Yes
() qw// Word list No
// m// Pattern match Yes
s/// s/// Pattern Substitution Yes
y/// tr/// Character substitution No
"" qr// Regular expression Yes

OK, that's impressive, but what does interpolate mean?

Think 'substitute' when you see the word 'interpolate'.

So when you use double-quotes or the other interpolatable (is that a word?) quote methods above, a variable in the quoted string will render the value held by that variable, not the name of the variable.

Interpolation substitutes the value stored in a variable for the name of the variable.

Here's what I mean:

print "\n" . "=" x20 . " quotes 1"."=" x20 . "\n";
print "\$var: $var\n"; # <--- double quotes
print '\$var: $var\n'; # <--- single quotes
print "\n" . "=" x20 . " All Done " . "=" x20 ."\n";

quotes 1

Using quote smartly, we can print a statement with apostrophes, a single-quoted string, or a variable as part of another word.

print "\n" . "=" x20 . " quotes 2 "."=" x20 . "\n";
my $word="un";
print "Mr. O'Brien, I'm very ${word}happy that you can't 'see things my way'!\n";
print "\n" . "=" x20 . " All Done " . "=" x20 ."\n";

quotes 2

Note the unusual formatting for $word in the print statement -- ${word}happy.

We can't use something like $wordhappy since Perl would look for a variable named that. We have to use the braces to separate the variable name from the text.

Recall that a string inside braces is interpolated.

Interpolation can also be used to concatenate strings!

print "\n" . "=" x20 . " quotes "."=" x20 . "\n";
my $a="What";
my $b="do you";
my $c="$a $b think you're doing?\n";
print $c;
print "\n" . "=" x20 . " All Done " . "=" x20 ."\n";

quotes 3

-30-