Skip to content

Instantly share code, notes, and snippets.

@neilb
Created April 4, 2021 11:03
Show Gist options
  • Select an option

  • Save neilb/cf9344c61cd3cc5c009a86c749ba3cea to your computer and use it in GitHub Desktop.

Select an option

Save neilb/cf9344c61cd3cc5c009a86c749ba3cea to your computer and use it in GitHub Desktop.

Revisions

  1. neilb created this gist Apr 4, 2021.
    34 changes: 34 additions & 0 deletions optionally.pm
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    package optionally;

    # don't use this
    #
    # this was an experiment in loading modules optionally, so you can write:
    #
    # use optionally;
    # optionally use Module::Foo 1.23 qw/ function1 function2 /;
    #

    use strict;
    use warnings;

    use Keyword::Simple ();
    use Carp qw/ croak /;
    use Module::Runtime qw/ require_module /;
    use Class::Unload ();

    sub import
    {
    my $importing_package = caller;

    Keyword::Simple::define('optionally' => sub {
    my $line = shift;

    my ($matched, $action, $module, $rest) = ( $$line =~ m!\A(\s*(\S+)\s+(\S+)\s*(.*?);)! )
    or croak "syntax error near 'optionally'";
    substr($$line, 0, length($matched)) = "";

    eval "package $importing_package; $matched";
    });
    }

    1;