There are three types of variables in perl: Scalar, arrays of scalars and hashes. Lets learn them one by one with the help of examples.
Scalars
Scalars are single data unit. A scalar can be integer, float, string etc. Scalar variables are prefixed with “$” sign. Lets have a look at the following perl script where we have three scalar variables.
#!/usr/bin/perl # Integer $age = 29; # String $name = "Chaitanya Singh"; # Float $height = 180.88; print "Name: $name\n"; print "Age: $age\n"; print "Height: $height\n";
Output:
Name: Chaitanya Singh Age: 29 Height: 180.88
Arrays
Arrays are ordered list of scalars, Array variables are prefixed with “@” sign as shown in the example below:
#!/usr/bin/perl @friends = ("Ajeet", "Leo", "Rahul", "Dhruv"); print "\$friends[0] = $friends[0]\n"; print "\$friends[1] = $friends[1]\n"; print "\$friends[2] = $friends[2]\n"; print "\$friends[3] = $friends[3]\n";
Output:
$friends[0] = Ajeet $friends[1] = Leo $friends[2] = Rahul $friends[3] = Dhruv
Hashes (also known as associative arrays)
Hashes are group of key-value pairs. Hash variables are prefixed with “%” sign. Lets have a look at the example below:
#!/usr/bin/perl %age = ('Chaitanya Singh', 29, 'Ajeet', 28, 'Lisa', 25); print "\$age{'Lisa'}: $age{'Lisa'}\n"; print "\$age{'Chaitanya Singh'}: $age{'Chaitanya Singh'}\n"; print "\$age{'Ajeet'}: $age{'Ajeet'}\n";
Output:
$age{'Lisa'}: 25 $age{'Chaitanya Singh'}: 29 $age{'Ajeet'}: 28
Leave a Reply