SYNOPSIS

    my $guard = guard { ... };

      # or

    my $guard = scope_guard \&handler;

      # or

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

    $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 \*(C`Scope::Guard\*(C' 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 \*(L"promises\*(R" to be made that are automatically honoured by perl's garbage collector.

For more information, see: <http://www.drdobbs.com/cpp/184403758>

METHODS

new

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

# or

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

The \*(C`new\*(C' method creates a new \*(C`Scope::Guard\*(C' object which calls the supplied handler when its \*(C`DESTROY\*(C' method is called, typically at the end of the scope.

dismiss

$guard->dismiss();

# or

$guard->dismiss(1);

\*(C`dismiss\*(C' detaches the handler from the \*(C`Scope::Guard\*(C' object. This revokes the \*(L"promise\*(R" to call the handler when the object is destroyed.

The handler can be re-enabled by calling:

$guard->dismiss(0);

EXPORTS

guard

\*(C`guard\*(C' takes a block and returns a new \*(C`Scope::Guard\*(C' object. It can be used as a shorthand for:

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

e.g.

my $guard = guard { ... };

Note: calling \*(C`guard\*(C' anonymously, i.e. in void context, will raise an exception. This is because anonymous guards are destroyed immediately (rather than at the end of the scope), which is unlikely to be the desired behaviour.

scope_guard

\*(C`scope_guard\*(C' is the same as \*(C`guard\*(C', but it takes 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;

As with \*(C`guard\*(C', calling \*(C`scope_guard\*(C' in void context will raise an exception.

VERSION

0.20

RELATED TO Scope::Guard…

  • B::Hooks::EndOfScope

  • End

  • Guard

  • Hook::Scope

  • Object::Destroyer

  • Perl::AtEndOfScope

  • ReleaseAction

  • Scope::local_OnExit

  • Scope::OnExit

  • Sub::ScopeFinalizer

  • Value::Canary

AUTHOR

chocolateboy <[email protected]>

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.