Saturday, August 20, 2011

How to Initialize or Clear an Array in Perl



Method 1: Assign an Empty List (Recommended)

The simplest and most highly recommended approach is to reassign the array to an empty list
my @array = ();


Method 2: Modify the Last Element's Index

In Perl, $#array represents the index of the last element in the array. Because Perl arrays are zero-indexed, this value is always one less than the array's total length.

You can manually change the length of the array by assigning a new value to $#array. By setting this index to -1, you destroy all existing values and completely clear the array.
$#array = -1;

No comments: