7.3 Waiter, I have a variable in my string!

Let's say we have the $firstname variable containing the first name of a person (Tak), and $balance variable containing the bank balance of the same person (assume it is $20,000,000). We may want to print the following:

Tak has $20000000 in the bank.

Alright, let's focus on how to get this printed, rather than the truth of the statement!

One obvious method is as follows:

print $firstname.' has '.$balance.' in the bank.';

However, this method uses a lot of concatenation operators (the periods). An easier method is as folows:

print "$firstname has $balance in the bank.";

The use of double quotes " tells the Perl interpreter that there may be variables embedded in the string. The double quotes also creates a ``in a string'' context, which provides enough clue to interpret $firstname as is (it already has a string) and automatically convert the value of $balance to a string prior to being utilized in the double quote context.

An immediate question is: what if we want to use the dollar symbol for the amount? In order to print a special symbol, such as the dollar sign, verbatim, we have to escape it as follows:

print "$firstname has \$$balance in the bank.";

The backslash symbol '\' is the escape symbol, it tells Perl not to interpret any special meaning in the following character. Together, \$ means just the dollar symbol, not as a prefix of a scalar variable. You can use the backslash method to escape quotes, including the double quote symbol!

Copyright © 2008-05-09 by Tak Auyeung