Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #207 Allocate a list that is automatically deallocated

Allocate a list a containing n elements (n assumed to be too large for a stack) that is automatically deallocated when the program exits the scope it is declared in.

{
    my @a = (undef) x $n;
    # scope ends at closing brace
} 

Normally it is not necessary to initialise an array with a certain number of elements because Perl arrays grow or shrink as necessary. Simply `my @a;` is idiomatic and will work fine.

I chose `undef` because it is the scalar value that takes the least amount of memory.
  integer, dimension(:), allocatable :: a
  allocate (a(n))

New implementation...
< >
tkoenig