Thursday, October 23, 2008

Perl RAII test banner

Wrote a somewhat neat Perl trick today:




    file RAII_Test_Banner.pm:

    {
    package RAII_Test_Banner;

    sub new {
    my $self = {};
    $self->{'message'} = shift;
    bless $self;

    print "START: $self->{message}\n";

    return $self;
    }

    sub DESTROY {
    my $self = shift;
    print "END: $self->{message}\n";
    }

    }


    if( $::TEST ) {
    {
    my $t = RAII_Test_Banner("Example of RAII_Test_Banner usage");
    print "something like START: Example ... should be printed above\n";
    print "This is inside\n";
    print "something like END: Example ... should be printed above\n";
    }
    }

    1;









This is just a Perl version of a C++ library I wrote years ago, when I first learned about RAII (Resource Allocation is Initialization) - aka using automatic scoping to reduce the need to write code that matches start and end.

I had not realized until today that Perl had deterministic finalization - at least for variables that are not referred to by live references.

IMHO one of the biggest weaknesses of Java is lack of deterministic finalization.

No comments:

Post a Comment