Using Variables
First, a regular variable in Perl is always preceeded by the $ sign. So, if you want a variable named adrevenue, you would have to write it as:
$adrevenue
Number Values
Now, we need to give this variable a value. This is often done when the variable is defined. To start, lets give it a numerical value. To do this, we need to set the variable equal to a number using the = sign, and end the statement with a semicolon:$adrevenue=100;
You can now use the variable inside your print statement to output the value of the $adrevenue variable:
$adrevenue=100;
print "The ad revenue for my site today is $adrevenue dollars.";
This just prints the sentence:
The ad revenue for my site today is 100 dollars.
String Values
To give a variable a string value (text, text with numbers), we need to surround the value using single quotes or double quotes. There is a difference in using the single or double quotes though. If you use single quotes, your string is taken as-is:
$my_stomach='full';
print 'My stomach feels $my_stomach.';
This gives $my_stomach a value of full, but because we used single quotes with our print statement, the value of the $my_stomach variable is not printed:
My stomach feels $my_stomach.
Since we used single quotes around the printed string, Perl sees the variable name as simply part of a literal string and prints it as-is rather than using its value.
The use of double quotes allows you to use other variables as part of the definition of a variable. It would now recognize the $ sign as setting off another variable and not as part of the string. So, now you could use something like this:
$my_stomach='full';
$full_sentence="My stomach feels $my_stomach.";
print "$full_sentence";
Now, the value of $my_stomach is used as part of the $full_sentence variable. This can be very handy at times. Now, it would print the following sentence:
My stomach feels full.
Use Them
Now, your Perl script can include some vairables (though they don't serve much purpose just yet). Here is a sample script using what we have so far:
#!/usr/bin/perl
$adrevenue=100;
$my_stomach='full';
$full_sentence="My stomach feels $my_stomach.";
print "Content-type: text/html\n\n";
print <<ENDHTML;
<html>
<head>
<title>Perl Variable Test</title>
</head>
<body>
I wish I could make $adrevenue dollars a day from my web site!
<p>
$full_sentence
</body>
</htmL>
ENDHTML
Now, this prints a wonderful HTML document that says:
I wish I could make 100 dollars a day from my web site!
My stomach feels full.
You can see the script display the HTML example above with the example link below:
Well, that's it for variables for now. Let's go on to Perl Operators.
Copyright © 1997-2008 The Web Design Resource. All rights reserved. Disclaimer.
