$num=5;
$stuff = "chocolate truffles";
$user = $ENV{USER};
In these examples, Perl assigns 5 to the numeric variable $num, "chocolate truffles" to the variable $stuff, and the value of the USER environment variable to $user.
This is a good time to note that there are several distinct ways to use quotation marks in a Perl script. Let's look at the differences among single quotation marks, double quotation marks, backticks, and the backslash character and then follow up with some examples.
· Single quotation marks, as in the preceding example, will always get you exactly what's inside the quotation marks--any characters that might otherwise have special meaning (like the dollar sign or the backslash) are treated literally.
· Use double quotation marks when you want to assign a string that contains special characters that need to be interpreted.
· The backslash is used to escape (treat literally) a single character (such as $ or *) that might otherwise be treated as a special character.
· Use backticks to indicate that the string is a Linux command that should be executed, with the results assigned to a variable.
Now let's look at some examples that show when to use each method of quoting:
$user = $ENV{USER};
print 'Good Morning $user';
Yields: Good Morning $user
$user = $ENV{USER};
print "Good Morning $user";
Yields: Good Morning hermie
In the first case, the results would probably not be what you wanted. The single quotation marks caused Perl to not treat $user as a variable. In the second case, the results look much better. The double quotation marks allowed Perl to substitute the value of $user in the string.
Here's another example that demonstrates a common error:
$costmsg = "Price is $5.00";
print "$costmsg";
Yields: Price is .00
We thought enough to quote the string, but the dollar sign tells Perl to use the value in the $5 variable, which is as yet undefined. We can easily solve the problem by prefixing the dollar sign with a backslash, as shown here:
$costmsg = "Price is \$5.00";
print "$costmsg";
Actual result: Price is $5.00
Finally, here's an example using backticks to execute a Linux command and capture the results in a Perl variable:
$currdir = 'pwd'
print "Current directory is $pwd";
Yields: Current directory is /home/hermie
Previous Lesson: Perl Basics
Next Lesson: Perl Arguments
|
![]() |
|
| <Send This Link to a Friend> <Help> <Bookmark This Page> | ||