evalEmpire / Mite

Mite - A zero dependency, fast loading, Moose-like Perl module
Other
3 stars 1 forks source link

Add code ref defaults #4

Closed schwern closed 10 years ago

schwern commented 10 years ago
has message =>
    default => sub { ... };

Take into account...

Here is a good example.

use strict;
use warnings;

my $start_time = time;
has start_time
    default => sub { $start_time };

One option, rather than dumping the code ref at compile time, to use the code ref passed into has() at run time. This seems to me the most robust solution. The compiled code will use a global variable for the default, $start_time_DEFAULT->($_[0]), or something. At runtime, has(), instead of being a complete no-op, will populate $start_time_DEFAULT. This should not incur a significant startup penalty.

Another is to use Data::Dump::Streamer to expand the code ref at compilation time and put it into the .mite file. This requires that DDS does its job right. It also means any closures based on variables set at runtime aren't going to work as expected, they will be hard coded at compile time. The advantage is no startup penalty.

One work around is to make users use state variables instead.

has start_time
    default => sub {
        state $start_time = time;
        return $start_time
    };
schwern commented 10 years ago

Did it using the method of having has() put the code ref into a magic global at runtime.