First ... Back ... Next ... Last ... (Notes home)

Types of Arrays in Perl

Arrays are ways of grouping related data under one variable name. It's easy and fast to access particular array elements (members), or to update or add elements. In Perl, array elements do not need to be the same data type (i.e., integers or strings), and array elements do not need to be contiguously numbered. There are two types of arrays in Perl. Here is more detail about the first type, regular arrays.

  • Regular arrays have integer indexes. From the programmer's point of view, array elements are stored and may be accessed continuously in memory. Example:
    my @arr;
    $arr[0] = "hello";
    $arr[1] = "goodbye";
    $arr[2] = "yesterday";
    $arr[3] = "today";
    $arr[4] = "tomorrow";
    foreach (@arr) { print $_ . "\n"; }
    
  • Regular arrays do not need to have contiguous indexes (0..1..2, etc.), but often do. If you skip around, only the values you create will exist. Example: $arr[99] = "goodnight"
  • The values for regular arrays can be nearly anything, including other arrays, data structures and references. Unlike most other languages, the content type for a given array does not need to be the same for all elements. Example:
    my @arr = ("hello", 2, 3.222);
  • There are several functions for creating new values in arrays. These include:
    • pop: pops and returns the last value of an array, shorterning the array by one
    • shift: pops and returns the first value of an array
    • push: adds a value to the end of an array
    • unshift: adds a value to the start of an array
    • splice: adds a value in the midst of an array
  • There is a special variable to count the number of items in an array. Example:
    print "There are $#arr values\n";

First ... Back ... Next ... Last ... (Notes home)

UAF Computer Science
Prof. Greg Newby