The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Sub::Inject - Inject subroutines into a lexical scope

VERSION

version 0.2.0

SYNOPSIS

    use Sub::Inject;   # requires perl 5.18+

    {
        BEGIN { Sub::Inject::sub_inject( 'one', sub { say "One!" } ); }
        one();
    }

    one();    # throws "Undefined subroutine &main::one called"

DESCRIPTION

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!" } );
    }

NAME

Sub::Inject - Inject subroutines into a lexical scope

HOW IT WORKS

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

FUNCTIONS

sub_inject

    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.

Throws an error if called at runtime.

ACKNOWLEDGEMENTS

This code is a fork of "Lexical.xs" file from Exporter-Lexical distribution by Jesse Luehrs.

SEE ALSO

"Lexical Subroutines" in perlsub

"The 'lexical_subs' feature" in feature

Exporter::Lexical and lexically

AUTHOR

Adriano Ferreira <ferreira@cpan.org>

CONTRIBUTOR

Adriano Ferreira <a.r.ferreira@gmail.com>

COPYRIGHT AND LICENSE

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.