Data types specify the type of data that a valid Perl variable can hold. Perl is a loosely typed language. There is no need to specify a type for the data while using in the Perl program. The Perl interpreter will choose the type based on the context of the data itself.
There are 3 data types in Perl as follows:
- Scalars
- Arrays
- Hashes(Associative Arrays)
1. Scalars:
It is a single unit of data that can be an integer number, floating-point, a character, a string, a paragraph, or an entire web page. To know more about scalars please refer to Scalars in Perl.
Example:
Perl
$age = 1;
$name = "ABC" ;
$salary = 21.5;
print "Age = $age\n" ;
print "Name = $name\n" ;
print "Salary = $salary\n" ;
|
Output:
Age = 1
Name = ABC
Salary = 21.5
Scalar Operations: There are many operations that can be performed on the scalar data types like addition, subtraction, multiplication, etc.
Example:
Perl
$str = "GFG" . " is the best" ;
$num = 1 + 0;
$mul = 4 * 9;
$mix = $str . $num ;
print "str = $str\n" ;
print "num = $num\n" ;
print "mul = $mul\n" ;
print "mix = $mix\n" ;
|
Output:
str = GFG is the best
num = 1
mul = 36
mix = GFG is the best1
2. Arrays:
An array is a variable that stores the value of the same data type in the form of a list. To declare an array in Perl, we use ‘@’ sign in front of the variable name.
@age=(10, 20, 30)
It will create an array of integers that contains the values 10, 20, and 30. To access a single element of an array, we use the ‘$’ sign.
$age[0]
It will produce an output of 10. To know more about arrays please refer to Arrays in Perl
Example:
Perl
@ages = (33, 31, 27);
@names = ( "Geeks" , "for" , "Geeks" );
print "\$ages[0] = $ages[0]\n" ;
print "\$ages[1] = $ages[1]\n" ;
print "\$ages[2] = $ages[2]\n" ;
print "\$names[0] = $names[0]\n" ;
print "\$names[1] = $names[1]\n" ;
print "\$names[2] = $names[2]\n" ;
|
Output:
$ages[0] = 33
$ages[1] = 31
$ages[2] = 27
$names[0] = Geeks
$names[1] = for
$names[2] = Geeks
3. Hashes(Associative Arrays):
It is a set of key-value pair. It is also termed the Associative Arrays. To declare a hash in Perl, we use the ‘%’ sign. To access the particular value, we use the ‘$’ symbol which is followed by the key in braces.
Example:
Perl
%data = ( 'GFG' , 7, 'for' , 4, 'Geeks' , 11);
print "\$data{'GFG'} = $data{'GFG'}\n" ;
print "\$data{'for'} = $data{'for'}\n" ;
print "\$data{'Geeks'} = $data{'Geeks'}\n" ;
|
Output:
$data{'GFG'} = 7
$data{'for'} = 4
$data{'Geeks'} = 11
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
22 Jun, 2022
Like Article
Save Article