NAME

Scope::Guard - lexically scoped resource management

SYNOPSIS

my $guard = guard { ... };

  # or

my $guard = scope_guard \&handler; # or sub { ... } or $handler

  # or

my $guard = Scope::Guard->new(\&handler); # or sub { ... } or $handler

$guard->dismiss(); # disable the handler

DESCRIPTION

This module provides a convenient way to perform cleanup or other forms of resource management at the end of a scope. It is particularly useful when dealing with exceptions: the Scope::Guard constructor takes a reference to a subroutine that is guaranteed to be called even if the thread of execution is aborted prematurely. This effectively allows lexically-scoped "promises" to be made that are automatically honoured by perl's garbage collector.

For more information, see: http://www.cuj.com/documents/s=8000/cujcexp1812alexandr/

METHODS

new

usage

my $guard = Scope::Guard->new(sub { ... });

  # or

my $guard = Scope::Guard->new(\&handler);

description

The new method creates a new Scope::Guard object which calls the supplied handler when its DESTROY method is called, typically when it goes out of scope.

dismiss

usage

$guard->dismiss();

  # or

$guard->dismiss(1);

description

dismiss detaches the handler from the Scope::Guard object. This revokes the "promise" to call the handler when the object is destroyed.

The handler can be re-enabled by calling:

$guard->dismiss(0);

EXPORTS

guard

guard takes a block and returns a new Scope::Guard object. It can be used as a shorthand for:

Scope::Guard->new(...)

e.g.

my $guard = guard { ... };

- or it can be called in void context to create a guard for the current scope e.g.

guard { ... };

Because there is no way to dismiss the guard in the latter case, it is assumed that the block knows how to deal with situations in which the resource has already been managed e.g.

    guard {
	unless ($resource->disposed) {
            $resource->dispose;
	}
    }

scope_guard

scope_guard is the same as guard, but it takes a scalar (e.g. a code ref) rather than a block. e.g.

my $guard = scope_guard \&handler;

or:

my $guard = scope_guard sub { ... };

or:

my $guard = scope_guard $handler;

Like guard, it can be called in void context to install an anonymous guard in the current scope.

VERSION

0.10

SEE ALSO

AUTHOR

chocolateboy: <chocolate@cpan.org>

COPYRIGHT

Copyright (c) 2005-2010, chocolateboy.

This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.