Search code examples
perl

Removing array elements in Perl


I want to remove the entire array. Currently I do @array=(); Does it remove the elements and clears the memory , garbage collected? If not do i need to use Splice?.


Solution

    • It's very very odd that you need to do this. Proper use of my means it's very rare that one needs to empty an array.

    • @array = (); will free the elements and call any destructors as necessary. In other words, the elements will be garbage collected (before the operation even ends) if they are not used elsewhere, as desired.

    • @array = (); does not free the underlying array buffer. This is a good thing. undef @array; would force the memory to be deallocated, which will force numerous allocations when you start putting more elements in the array.


    So,

    • If you want free an array because you'll never use it again, limit its scope to where you need it by placing the my @array; at the correct location.

        {
           my @array;
           ...
        } # Elements of @array garbage collected here.
      
    • If you want to empty an array you will reuse, use @array = ();.

        my @array;
        while (...) {
           if (...) {
              push @array, ...;
           } else {
              ... use @array ...
              @array = ();  # Elements of @array garbage collected here.
           }
        }
      
    • Don't use undef @array;.


    You can use splice if it's convenient.

     say for @array;
     @array = ();
    

    could be written as

     say for splice(@array);