Brought to you by molecularsciences.org.
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License.
This publication may not be redistributed without this notice.

Perl Variables

Perl is different from popular languages like C, C++, and Java. In C, variable is name of a memory location. You can store a piece of data in it like an interger, a floating point number, a character etc. Before using a variable, you have to declare it along with it type (whether it is an integer, character, etc.). In Perl you don't have to deal with all that nonsense. All you do is just use a variable.

A perl variable is different from a C variable. In Perl, a variable can be a scalar, array, hash, subroutine, or a typeglob. Perplexed. Don't be. A scalar performs all the functions of a C variable and a lot more. In Perl, array is also a variable. You will see how powerful your code will become if you can treat an array like you treat a variable. Hash used to be called an associative array. It is a different kind of an array, an unordered array. A subroutine is much like a C function and a lot more. A typeglob is another interesting topic. Each of these data types are distinguished by the first symbol of the variable. Everything starting with $ is a scalar. Everything starting with @ is an array and so on. See the table below.

Variable Syntax

Type
Character
Example
Is a name for:
Scalar
$
$cents An individual value  (number or string)
Array
@
@large a list of values, keyed by number
Hash
%
%interest A group of values, keyed by string
Subroutine
&
&how A callable chunk of Perl code
Typeglob
*
*struck Everything named struck

Just like C, Perl variables also have types. When you use a variable, Perl automatically declares and initializes it. All scalars are initialized to 0 by default. All arrays are initialized to NULL by default. All strings are initialized to empty string by default.