Perl Programming Part I :: Perl Data Types
Monday, April 12, 2010
0
comments
Type | Identifier | Containable Data |
---|---|---|
Scalar | $ | Number or string |
Array | @ | List of values indexed by number |
Hash | % | Group of values indexed by string |
Subroutine | & | Subroutine callable by Perl |
References | \ | References to anything of that name |
Scalar Data Types
In Perl the scalar data type is used in 3 contexts.
- String context
- Numeric context
- Miscellaneous context
- $name = "Kanishka" ;
Numeric Context
- $height = 34 ;
Miscellaneous Context
- $temperature = 31.47;
Array Data Types
An array in Perl can contain number of scalar variables. The containing scalars may be related to different contexts. for example the same array can contain numeric data as well as string data.
Declaring an array
- @myArr=("Kaniskha",21,"Galle");
in above code an array called myArr is created and. 3 different data are stored inside it.
- @myArr=();
above code makes the myArr empty.
Note : Arrays in perl is not fixed. so the programmer can expand the size of any array when he/she need.
perl arrays are zero based.
Assigning Values to Arrays
arrays can be assigned in 2 ways. Either assign at once or assign individually. This is up to the programmer.
Assigning an array at once
- @myArr=("Kaniskha",21,"Galle");
Assigning an array individually
- @myArr=();
- $myArr[0]="Kaniskha";
- $myArr[1]=21;
- $myArr[2]="Galle";
Hash Data Types
In Perl Hash data type is an unordered set of scalar data indexed by string scalar data item. If you are familiar with PHP you may be heared about associative arrays. The hash data type in perl is identical to an associative array. Perl provides this hash data type using a hash table algorithm.
Like the standard array hash also can be populated individually.
Declaring a Hash ( Associative Array )
- %fruits = ( "O" => "Orange" , "A" => "Apple" , "B" => "Banana");
Please note that the => operator is equivalent to a comma. The main purpose of => operator is make association between pairs.
So we can write above code segment as following statement also.
- %fruits = ( "O" ,"Orange" , "A" , "Apple" , "B" , "Banana");
Like standard array , hash also can be populated by individually.
- $fruits{"O"}="Orange";
- $fruits{"A"}="Apple";
- $fruits{"B"}="Banana";
Labels: