Code Monkey home page Code Monkey logo

scope-guard's Introduction

Scope::Guard

Build Status CPAN Version

NAME

Scope::Guard - lexically-scoped resource management

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 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: https://www.drdobbs.com/cpp/184403758

METHODS

new

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

  # or

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

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

dismiss

$guard->dismiss();

  # or

$guard->dismiss(1);

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 { ... };

Note: calling guard 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

scope_guard is the same as guard, 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 guard, calling scope_guard in void context will raise an exception.

VERSION

0.21

SEE ALSO

AUTHOR

chocolateboy

COPYRIGHT AND LICENSE

Copyright ยฉ 2005-2021 by chocolateboy.

This is free software; you can redistribute it and/or modify it under the terms of the Artistic License 2.0.

scope-guard's People

Contributors

chocolateboy avatar jraspass avatar karenetheridge avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

scope-guard's Issues

Add feature to pass additional arguments on to coderef

Thank you for this great module. I've written minimal versions of this multiple times and have just found this concise solution on CPAN! ๐Ÿ‘

Would you mind adding a feature that you can provide additional arguments that get passed on to the provided coderef?

my $guard = guard { do_something_with_foo(@_) }, $foo, $bar, ...;

The difference to

my $guard = guard { do_something_with_foo($foo, $bar, ...) };

is obviously the execution time of $foo etc. I have a long living LWP::UserAgent object and need to temporarily set its max_redirect to 0. I'd love to write this:

my $ua = LWP::Simple->new();
...
subtest "test some redirect" => sub {
    my $guard = guard { $ua->max_redirect(@_) }, $ua->max_redirect; # will restore original value 
    $ua->max_redirect(0); # temporarily
    ...
};
...

As far as I studied your code no existing code could be using any additional arguments and they could easily stored in @$self.

I'd send a PR if you consider adding this feature.

Lack of protection against fork

This is probably a design decision. But as this is not documented, I lean to consider it a bug / limitation.
The current implementation of Scope::Guard does not have the notion of the main process which created the guard.

This could lead to multiple execution of a guard, and most of the time this is probably not what we want/expect.

Here is a sample proof of concept showing the limitation

#!perl

use v5.32;

use Scope::Guard;

sub test {

    my $g1 = Scope::Guard->new( 
        sub { 
            say qq[guard 1 done from $$];
        }
    );
    
    if ( my $pid = fork() ) {
        say q[Parent: ], $$, q[ kid: ], $pid;
        sleep 2;        
    } else {
        sleep 1;
        say q[kid leaving];
        exit;
    }

    say q[done];
}

test();

Output:

> perl test.pl
Parent: 11887 kid: 11888
kid leaving
guard 1 done from 11888
done
guard 1 done from 11887

Most of the time these kinds of fork would happen from unpredictable locations while running some extra code, while holding a guard.

Adding a PID protection is pretty forward, and I can gladly provide a fix for it.
But before I'm curious to know your point of view, and if you also think this should be the default behavior.
Note that this could lead to main behavior change.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.