Logo

Programming-Idioms

History of Idiom 207 > diff from v2 to v3

Edit summary for version 3 by daxim:
New Perl implementation by user [daxim]

Version 2

2019-09-30, 05:19:42

Version 3

2019-09-30, 12:55:34

Idiom #207 allocate a list that is automatically deallocated

Allocate a list / array 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.

Idiom #207 allocate a list that is automatically deallocated

Allocate a list / array 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.

Code
{
    my @a = (undef) x $n;
    # scope ends at closing brace
} 
Comments bubble
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.