Perl has three data types: Scalars, arrays of scalars and hashes (also known as associative arrays, dictionaries or maps). In perl we need not to specify the type of data, the interpreter would choose it automatically based on the context of data.
For e.g. In the following code, I am assigning an integer and a string to two different variables without specifying any type. The interpreter would choose age as integer type and name as string type based on the data assigned to them.
#!/usr/bin/perl $age=29; $name="Chaitanya";
Scalars
Scalars are single data unit. It can be a number, float, character, string etc. In perl, they are prefixed by a dollar sign($). Read about them in detail here.
For example:
$num1=51; $str1="beginnersbook"; $num2=2.9; $str2="hello";
Arrays
They are ordered list of scalars, prefixed with “@” sign. Index starts with 0 which means to access the first element of array, we need to use index value as 0 (zero). For eg.
#!/usr/bin/perl @pincode = (301019, 282005, 101010); print "\$pincode[0] = $pincode[0]\n";
Output:
pincode[0]= 301019
If you are wondering about the backslash (\) used in the print instruction, it is used to avoid the interpolation of first occurrence of pincode[0]. You can read more about arrays here.
Hashes
They are unordered group of key-value pairs. They are prefixed with percent(%) sign.
#!/usr/bin/perl %ages = ('Chaitanya', 29, 'Ajeet', 28, 'Tom', 40);
Here “ages” is a hash that has key value pairs. where key is a name and value is age. To access the age of Ajeet we use $age{‘Ajeet’} instruction.
Read more about hashes with examples here.
Leave a Reply