Perl Variables (Scalars)
This document was written by CS 290W TA David Corcoran and was last
modified
Every programming language handles variables differently. In C++ or Java
you must declare your variable along with its type. For example:
int length;
int width;
char name[50];
would allow you to store an integer in length and width and a name up to
50 characters under name. It would not be possible to say something like:
length = "CS 290W";
name = 500;
Why? Because length only accepts numbers and name only accepts
characters. In Perl you can forget all those "nasty" type declarations
because you do not have int, float, String, char, etc. Instead you have
what is known as a scalar variable.
Scalars can contain all types of data. Floats, Strings, Integers, etc to
name a few. Although their variable names stay constant throughout the
program, a variable may contain an Integer at one point and then a String
at another. For this reason it is VERY important to comment Perl scripts
well, because can occasionally get a bit confusing.
Scalars begin with a dollar sign and then the variable name. Below are a
few examples of scalar variables under Perl:
$Name
$Bob_Age
$Size_At_1
Scalar variables MUST begin with a letter after the dollar sign.
After that you may choose whether to use letters, numbers, or
underscores. The following are illegal:
$1_Name
$2_Bob_Age
$3_Size_At_1
Please take particular caution when choosing variable names. A
variable such as $a2b3c4
is not very helpful to
someone reading your code. But, $Matrix_Rows
is
helpful.
You may want to also keep track of your variable types. One popular
method is known as Hungarian Notation. What this means is that you
start every variable with one or two lowercase characters describing
its type. For example see if you can tell what type of data the
following variables hold:
$iAge
$sName
$fDivide
Hopefully you might have guessed that $iAge is an Integer, $sName is a
String, and $fDivide is a floating point variable. Using Hungarian
Notation will greatly help you in debugging your code by allowing you
to distinguish different variable types. Although Perl allows you to
do the following...
$sName = "Dave";
$sName = 100;
...we strongly suggest you NOT do that. Instead, create a new
variable to hold the integer type to avoid further confusion later on
in your program.