Created
August 1, 2012 08:22
-
-
Save tobyink/3224932 to your computer and use it in GitHub Desktop.
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
package returning; | |
use 5.008001; | |
use strict; | |
BEGIN { | |
$returning::AUTHORITY = 'cpan:TOBYINK'; | |
$returning::VERSION = '0.001'; | |
} | |
use Carp 0 ; | |
use Devel::Declare 0.006007 (); | |
use Devel::Declare::Context::Simple 0 (); | |
sub import | |
{ | |
my $class = shift; | |
my $default_target = caller; | |
foreach my $arg (@_) | |
{ | |
if (ref $arg eq 'HASH') | |
{ | |
my $target = $arg->{-into} || $default_target; | |
foreach my $f (keys %$arg) | |
{ | |
next unless $f =~ /^[^\W\d]\w*$/; | |
my $v = $arg->{$f}; | |
my $code = ('CODE' eq ref $v) ? $v : sub(){$v if $]}; | |
do { | |
no strict 'refs'; | |
*{ "$target\::$f" } = $code; | |
}; | |
$class->setup_for($target, $f); | |
} | |
} | |
elsif ($arg =~ /^[^\W\d]\w*$/) | |
{ | |
$class->setup_for($default_target, $arg); | |
} | |
else | |
{ | |
croak "unrecognised import argument to returning: $arg"; | |
} | |
} | |
} | |
sub setup_for | |
{ | |
my ($class, $target, $func) = @_; | |
Devel::Declare->setup_for( | |
$target => { | |
$func => { | |
const => sub { | |
my $ctx = Devel::Declare::Context::Simple->new; | |
$ctx->init(@_); | |
return $class->_transform($func, $ctx); | |
}, | |
}, | |
}, | |
); | |
} | |
sub _transform | |
{ | |
my ($class, $name, $ctx) = @_; | |
$ctx->skipspace; | |
my $linestr = $ctx->get_linestr; | |
if ($name eq substr $linestr, $ctx->offset, length $name) | |
{ | |
substr($linestr, $ctx->offset, length $name) = qq(return(&$name)); | |
warn "<<$linestr>>"; | |
$ctx->set_linestr($linestr); | |
} | |
return 0; | |
} | |
1; |
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
use 5.010; | |
use Test::More tests => 1; | |
use constant { | |
Affirmative => !0, | |
Negitive => !1, | |
}; | |
use returning qw(Affirmative Negitive); | |
sub test | |
{ | |
Affirmative; # this should be rewritten as: return(&Affimative); | |
Negitive; # this should be rewritten as: return(&Negitive); | |
} | |
ok test(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yet the following test passes...