Programming-Idioms

History of Idiom 209 > diff from v3 to v4

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

Version 3

2019-09-30, 08:04:05

Version 4

2019-09-30, 11:24:33

Idiom #209 Type with automatic deep deallocation

Declare a type t which contains a string s and an integer array n with variable size, and allocate a variable a of type t. Allocate v.s and v.n and set them to the values "Hello, world!" for s and [1,4,9,16,25], respectively. Deallocate v, automatically deallocating v.s and v.n (no memory leaks).

Idiom #209 Type with automatic deep deallocation

Declare a type t which contains a string s and an integer array n with variable size, and allocate a variable a of type t. Allocate v.s and v.n and set them to the values "Hello, world!" for s and [1,4,9,16,25], respectively. Deallocate v, automatically deallocating v.s and v.n (no memory leaks).

Imports
use Moops;
Code
class T {
    has 's', is => 'ro', isa => Str;
    has 'n', is => 'ro', isa => ArrayRef[Int];
}

{
    my $v = T->new(s => 'Hello, world!', n => [1,4,9,16,25]);
    # deallocation happens at closing brace, see explanation
}
Comments bubble
Declaration of the variable and object instantiation/allocation for the attributes is combined into one statement for convenience. Separating this into three steps is also possible with attributes declared 'rw' (read-write).

Perl objects are reference counted. <http://p3rl.org/perlref#DESCRIPTION> When $v falls out of scope, its count is decreased to 0 and the dead object is garbage collected. <http://p3rl.org/Devel::Refcount> The memory it occupied is made available again for Perl to reuse.