How to Create an Array in Perl

Arrays are a basic data structure used to hold numbered lists of information. Perl array variables begin with a "@" instead of the "$" used for simple variables. Each entry in the array is called an element and given an index used to access that entry.

Instructions

    • 1

      Declare the array and assign initial values by placing them inside parentheses, separated by commas.
      @groceryList = ("Apples","Milk","Cheese");

    • 2

      Print the array by simply giving it as a parameter to the print statement.
      print "@groceryList";

    • 3

      Access individual elements of the array by placing the index, enclosed in square brackets, after the array name, as follows.
      @groceryList[1]
      Since Perl array indices start at 0, the above refers to "Milk".

    • 4

      Use negative numbers for the index to count backwards. For example, @groceryList[-1]gives the last element in the array, which is "Cheese."

    • 5

      Determine the size of the array by forcing it to a scalar, using the construct scalar @groceryList.

    • 6

      Sort the array using the sort function, as in the following:
      @groceryList = sort(@groceryList);

Tips & Warnings

  • Indices begin with 0, rather than 1.

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured