Home » Perl Basics » 03 - Variables
3

Arrays

Array variable is a list of scalars

Arrays are nothing more than a list of scalar variables. Like scalar the name of the array is preceded by a special character. While scalars use $ arrays use @. As far the memory allocation is concerned, scalars and arrays are two different things. It means that you can use the same name for variables of different type.

  #!/usr/bin/perl –w
#date
# arrays type variable
@name = (“eric” , “marc” , “jo” , “mitch”);
print  “$name[0] “
print  “$name[1] “
print  “$name[2] “
print  “$name[3] “
#END
To create you own array:

 

  @name_of_your_array = (“element0” , “element1” , “element2” , “element3” etc.. )

NOTE: The first element of an array is element 0 and not element1.

To print an element of an array you use the same method as for a scalar but put at the end of the name of the array [N] where N is the number of the element you want to display. Another method allows you to print several values with the same print command.

  print “@name[0,1,3,2]”; 
you can print the elements in any order you want.
  print  “@name[0..3]”; 
you can print any bracket ….. All you need is “..” between the delimiters. However it needs to be going from lower to higher values.
  print “@name[0..$#name]”; 
Perl keeps an internal variable for each array with the number of the last element of that array. You can use it when you do not know how many elements an array has. It is very useful when creating an array from a file you know nothing about (log file for example). $#name_of_the_array will give you the number of the last element of your array.

 

NOTE : the array beginning at 0 the number of element you’re your array is $#name_of_your_array + 1.
NOTE: you may have notice above that to print a variable in an array we use $name_of_the_array and not @name_of_the_array. It is not always true and certain functions will require the @name_of_your_array as you were able to see in our second example.