Perl Programming Part I :: Perl Data Types

Monday, April 12, 2010 Posted by Kanishka Dilshan

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.
  1. String context
  2. Numeric context
  3. Miscellaneous context
String Context
  1. $name = "Kanishka" ;

Numeric Context
  1. $height = 34 ;

Miscellaneous Context
  1. $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
  1. @myArr=("Kaniskha",21,"Galle");

in above code an array called myArr is created and. 3 different data are stored inside it.
  1. @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
  1. @myArr=("Kaniskha",21,"Galle");

Assigning an array individually
  1. @myArr=();
  2. $myArr[0]="Kaniskha";
  3. $myArr[1]=21;
  4. $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 )
  1. %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.
  1. %fruits = ( "O" ,"Orange" , "A" , "Apple" , "B" , "Banana");

Like standard array , hash also can be populated by individually.
  1. $fruits{"O"}="Orange";
  2. $fruits{"A"}="Apple";
  3. $fruits{"B"}="Banana";
Labels:

Post a Comment