The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.


Sub::Deferrable - Optionally queue sub invocations for later.


Version 0.05


    use Sub::Deferrable;
    my $queue = Sub::Deferrable->new();
    my $sub  = $queue->make_deferrable( \&some_sub );
    $sub->(@args);              # Executes immediately
    $sub->(@more_args);         # Not executed
    $sub->(@yet_more_args);     # Not executed
    $queue->undefer;            # Both calls now executed synchronously;
                                # subsequent calls execute immediately.

Sub::Deferrable provides methods for wrapping a sub reference, giving it a split personality. In "normal" mode the wrapper simply calls the sub, passing along any arguments. In "deferred" mode, the wrapper creates an invocation object and saves it on a queue. When the queue is returned to "normal" mode, all invocations on the queue are executed immediately.


No exports.



Returns a new Sub::Deferrable object with an empty queue.

$self->mk_deferrable( \&some_sub )

Returns a new sub reference, which normally behaves like \&some_sub, but which saves an invocation of \&some_sub on the queue when in "deferred" mode.

An optional extra argument provides a sub reference to be applied to the invocation arguments at queueing time. If this argument is supplied, it is probably a reference to Storable::dclone, which will create a deep copy of the arguments and so break any reference pointers. This might be needed if, say, the arguments at invocation time might change before the queued sub is run.


Returns true when deferrable subs are queued; false when they are than invoked immediately.


Stop executing deferrable subs, and start queueing them instead. Repeated calls to $self->defer are equivalent to a single call; in particular, one call to $self->undefer will turn off deferral mode.


Stop queueing subs, and start executing them immediately. Any subs already queued are executed before undefer() returns.


Stop queueing subs, but discard any subs already queued.


On destruction, all queued subs are invoked. This is a failsafe; please do not write code that relies on this behavior. By the time this object is destroyed, it's likely too late to invoke your subs anyway, so this will probably crash your app. As you so richly deserve.


Budney, Len, <>


Not all subs are deferrable, by their nature. If the sub interacts with an open file or socket, for example, execution may fail later because the file or socket is closed. Presumably, you thought of that before you decided to make your sub deferrable.



Copyright 2005-2012 Grant Street Group. All rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.