Perl Array

List and array variables

Scalar variable allows you to store single element such as number or string. When you want to manage a collection or a list of scalar data you use list. Here are some examples of lists.

  1. ("Perl","array","tutorial");
  2. (5,7,9,10);
  3. (5,7,9,"Perl","list");
  4. (1..20);
  5. ();

We have five lists. In the line 1 we have a list which contains three string. Line 2 we have a list which contains 4 integer. Line 3 we have a list which contains 3 integer and 2 strings. Line 4 we have a list of 20 elements. A pair of period (..) is called range operator. Line 5 we have an empty list. Each scalar data in the list is called list element.

To store list to use throughout program you need array variable. Array variable is used to hold a list data. Different from scalar variable, array variable are prefixed with at sign(@). For example we have five array variables to store five lists above as follows:

  1. @str_array = ("Perl","array","tutorial");
  2. @int_array = (5,7,9,10);
  3. @mix_array = (5,7,9,"Perl","list");
  4. @rg_array = (1..20);
  5. @empty_array = ();

Array element can be accessed by using indices starting from zero (0). Perl uses square bracket to specify the index. For example to get the second element of array @str_array we use expression as follows:

  1. $str_array[1];

Be noticed that the dollar sign ($) is used instead of at sign (@). It is understandable that array element is scalar so ($) sign is used instead.

Operations on array

You can add or remove elements to/from an array. Here is a function list which allows you to do common operations on array:

  • push(@array,$element) add $element to the end of array @array
  • pop(@array) remove the last element of array @array and returns it.
  • unshift(@array,$element) add $element to the start of array @array
  • shift(@array) remove the first element from array @array and returns it.

Here is the code snippet to demonstrate each function above:

  1. @int =(1,3,5,2);
  2.  
  3. push(@int,10); #add 10 to @int
  4. print "@int\n";
  5.  
  6. $last = pop(@int); #remove 10 from @int
  7. print "@int\n";
  8.  
  9. unshift(@int,0); #add 0 to @int
  10. print "@int\n";
  11.  
  12.  
  13. $start = shift(@int); # add 0 to @int
  14. print "@int\n";

Be noticed that the line 4, 7, 10 and 14 is used to print the array.