Variables and Data Types
Learn how you can use variables to store data and understand the differences among various data types available in Perl.
We'll cover the following...
Variables
A variable in any programming language is a named piece of computer memory to hold some program data. Variables are an essential part of a computer program.
You can declare a variable in Perl using a $ sign followed by its name, e.g., $myVar.
Consider the following Perl code where we store data in variables and display them on the screen.
Escape characters
We use escape characters for a particular purpose in Perl to achieve a specific functionality, e.g., in the above code snippet, for instance, \n does not represent the character ‘n’, but a new line or line break. We can use many other escape characters using the \ operator in our code.Similarly, there are many escape characters which are given below:
Data types
There are different data types available in Perl for different purposes. Some of them have been presented below:
- Boolean
- Integer
- Float
- Array
- String
Unlike other languages such as C++ or Java, Perl does not require defining variables along with a specific data type. The type of a variable is picked based on the value assigned to it.
Here is a brief overview of the types:
Boolean
Boolean data type is used to store true or false values. The numeric value 0 is used to represent false, whereas any other numeric value represents true. Let’s look at the code below:
Integer
An integer is a positive or negative whole number. Perl allows you to assign integer constants in decimal, hexadecimal, octal or binary numbering systems. Consider the following code:
Here the variable values are interspersed with the constant text in the print statement.
Float
Floating point numbers, doubles or simply called floats are decimal numbers.
Array
An array is like a list of values (similar or
of different data types). The simplest form of an array is indexed by an integer, and ordered by the index, with the first element lying at index 0. We use @ to initiate an array with values enclosed in () pair of parenthesis. Look at the following code:
We will explore arrays in more detail in the chapter, Arrays.
String
A string is an array of characters. We can declare a string using either single quotes (') or double quotes (").
We will explore strings in more detail in the chapter, Strings.
This whole process of declaring variables and storing data in these variables is summed up in the following slide: