Perl Array Howto

This how-to comes with no guaratees other than the fact that these code segments were copy/pasted from code that I wrote and ran successfully.

Initialize (clear) an array.


    my @array = ();


$#array is the subscript of the last element of the array (which is one less than the length of the array, since arrays start from zero). Assigning to $#array changes the length of the array @array, hence you can destroy (or clear) all values of the array between the last element and the newly assigned position. By assigning -1, everything is destroyed and the array is cleared. I recommend the above solution to this one.

    $#array = -1;

Determine whether an array value exists, is defined, or is true.


    print "Value EXISTS, but may be undefined.\n"  if exists  $array[ $index ];
    print "Value is DEFINED, but may be false.\n"  if defined $array[ $index ];
    print "Value at array index $index is TRUE.\n" if         $array[ $index ];

Get the size of an array.


If you just want to print the size, this is the simplest way.

    print "size of array: " . @array . ".\n";


If you want to retain the size in a variable, just evaluate the array in implicit scalar context.

    $size = @array;
    print "size of array: $size.\n";

Explicit scalar context can be achieved by using the function scalar.

    $size = scalar @array;
    print "size of array: $size.\n";

Since the results are the same, I recommend the implicit solution.


There are also a number of other methods of getting the array size.

    $size = $#array + 1;


Alex BATKO <abatko AT>

Thanks to all those who have written with suggestions and comments.


Hi! If this document helped you figure out something you were stuck on; if it saved you time; if it relieved some frustration or anxiety... please consider donating. Thank you kindly!

Perhaps you are looking for web hosting? Hands down, the best web host I have ever experienced is DreamHost: They offer everything unlimited: storage, bandwidth, domains, subdomains, email accounts, MySQL databases. As well, they permit full shell access on Debian GNU/Linux. And they are employee owned and operated since 1997. Oh, and their web control panel is amazing! Use the URL above and the following promo code to save up to $47: ABATZPH5050