Is it possible use or require a Perl script without executing its statements?

后端 未结 3 1908
半阙折子戏
半阙折子戏 2021-02-05 09:06

I need to add unit testing to some old scripts, the scripts are all basically in the following form:

#!/usr/bin/perl

# Main code
foo();
bar();

# subs
sub foo {         


        
3条回答
  •  北海茫月
    2021-02-05 09:49

    Assuming you have no security concerns, wrap it in a sub { ... } and eval it:

    use File::Slurp "read_file";
    eval "package Script; sub {" . read_file("script") . "}";
    
    is(Script::foo(), "foo");
    

    (taking care that the eval isn't in scope of any lexicals that would be closed over by the script).

提交回复
热议问题