How can I know the length of a given array?

You have three options:

  1. Assing the array variable into a scalar variable, as in the previous slide.

    This is not recommended, because the code is confusing.

  2. Use the scalar function.


    $x = scalar (@array);
    # $x now contains the number of elements in @array.
  3. Use the special variable $#array_name to get the index value of the last element of @array_name.


    @fruits = ("apple", "orange", "banana", "melon");
    $a = $#fruits;      # $a is now 3;
    $b = $#fruits + 1;  # $b is now 4, i.e.
                        # the no. of elements in @fruits.

Table of Contents.
Next | Next.