Created
October 19, 2012 09:29
-
-
Save dex4er/3917158 to your computer and use it in GitHub Desktop.
Scope::Using
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use lib 'lib'; | |
package My::Class; | |
use Moose; | |
has 'ref' => (is => 'rw', clearer => 'clear_ref'); | |
sub DISPOSE { warn "$_[0]\->DISPOSE called"; $_[0]->clear_ref } | |
sub DESTROY { warn "memory leak of @_" if ${^GLOBAL_PHASE} and ${^GLOBAL_PHASE} eq 'DESTRUCT'; } | |
package main; | |
use Scope::Using; | |
using my $obj1 = My::Class->new(); | |
using my $obj2 = My::Class->new(); | |
$obj1->ref($obj2); | |
$obj2->ref($obj1); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl -c | |
package Scope::Using; | |
use strict; | |
use warnings; | |
our $VERSION = 0.00_01; | |
use Devel::Declare (); | |
use Guard (); | |
our @CARP_NOT = qw(Devel::Declare); | |
sub import { | |
my $class = shift; | |
my $caller = caller; | |
Devel::Declare->setup_for( | |
$caller, | |
{ using => { const => \&parser } } | |
); | |
no strict 'refs'; | |
*{$caller.'::using'} = sub ($) {}; | |
}; | |
our $prefix = ''; | |
sub get_linestr { | |
return substr Devel::Declare::get_linestr, length $prefix | |
}; | |
sub set_linestr { | |
return Devel::Declare::set_linestr $prefix . $_[0]; | |
}; | |
sub parser { | |
my ($keyword, $offset) = @_; | |
local $prefix = substr get_linestr, 0, $offset; | |
strip_keyword(); | |
my $linestr = get_linestr; | |
$linestr =~ s/\s*(?:(local|my|our|state)\s*)?(\$\w+|\(.*?\))// or die 'Syntax error'; | |
my ($scope, $decl) = ($1, $2); | |
my $before = ''; | |
$before .= "$scope $decl; " if defined $scope; | |
my @vars = $decl =~ /^\((.*)\)$/ | |
? split /\s*,\s*/, $1 | |
: $decl; | |
foreach my $var (@vars) { | |
$before .= "Guard::scope_guard { $var->DISPOSE if eval { $var->can('DISPOSE') } }; "; | |
}; | |
set_linestr($before . $linestr); | |
} | |
sub strip_space { | |
my $skip = Devel::Declare::toke_skipspace length $prefix; | |
set_linestr substr get_linestr, $skip; | |
} | |
sub strip_keyword { | |
strip_space; | |
get_linestr =~ /^(using)(?:\b|$)/ or die 'Could not match using keyword ', get_linestr; | |
$prefix .= $1; | |
return $1; | |
} | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment