public
Last active

  • Download Gist
BlockGiven.pm
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
package DB;
 
sub uplevel_args {
my @foo = caller($_[0]+1);
return @DB::args;
}
 
package BlockGiven;
use strict;
use Devel::Declare;
 
sub import {
my $class = shift;
my $caller = caller;
Devel::Declare->setup_for(
$caller => {
block_given => { const => \&_parser }
}
);
 
no strict 'refs';
*{$caller . "::block_given"} = \&block_given;
*{$caller . "::yield"} = \&yield;
}
 
sub _parser {
my ($Declarator, $Offset) = @_;
my $line = Devel::Declare::get_linestr;
 
if ("block_given?" eq substr($line, $Offset, length($Declarator) + 1)) {
substr($line, $Offset + length($Declarator), 1) = "";
Devel::Declare::set_linestr($line);
}
}
 
sub block_given() {
my @args = (DB::uplevel_args(1))[-1];
return (ref($args[-1]) eq "CODE")
}
 
sub yield {
(DB::uplevel_args(1))[-1]->(@_);
}
 
1;
test.pl
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
package main;
use 5.010;
use strict;
use lib '.';
use BlockGiven;
 
sub add_then {
my $arg1 = shift;
my $arg2 = shift;
 
if (block_given?) {
yield($arg1 + $arg2);
}
};
 
add_then(
1, 1,
sub {
my $ans = shift;
say "1 + 1 is $ans!";
}
);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.