Sub::Inject - Inject subroutines into a lexical scope
version 0.2.0
use Sub::Inject; # requires perl 5.18+ { BEGIN { Sub::Inject::sub_inject( 'one', sub { say "One!" } ); } one(); } one(); # throws "Undefined subroutine &main::one called"
This module allows to dynamically inject lexical subs during compilation. It is implemented using lexical subroutines introduced in perl 5.18.
This is a low level library. It is meant for cases where subroutine names and bodies are to be treated as data or not known in advance. Otherwise, lexical subs syntax is recommended. For instance,
use experimental qw(lexical_subs); state sub foo { say "One!" }
is the static equivalent of
BEGIN { Sub::Inject::sub_inject( 'one', sub { say "One!" } ); }
Used like
BEGIN { Sub::Inject::sub_inject('foo', sub { ... }) }
it works as
\state &foo = sub { ... };
That means:
The scope behavior is the same as the lexical sub statement
Being a "state" lexical guarantees the persistence of the association between the name and the subroutine
The reference aliasing operation means no copy is done
sub_inject($name, $code); sub_inject($name1, $code1, $name2, $code2);
Injects $code as a lexical subroutine named $name into the currently compiling scope. The same applies to multiple name / code pairs given as input.
$code
$name
Throws an error if called at runtime.
This code is a fork of "Lexical.xs" file from Exporter-Lexical distribution by Jesse Luehrs.
"Lexical Subroutines" in perlsub
"The 'lexical_subs' feature" in feature
Exporter::Lexical and lexically
Adriano Ferreira <ferreira@cpan.org>
Adriano Ferreira <a.r.ferreira@gmail.com>
This software is copyright (c) 2017 by Adriano Ferreira.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
To install Sub::Inject, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Sub::Inject
CPAN shell
perl -MCPAN -e shell install Sub::Inject
For more information on module installation, please visit the detailed CPAN module installation guide.