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

后端 未结 3 1913
半阙折子戏
半阙折子戏 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:53

    Ahh, the old "how do I unit test a program" question. The simplest trick is to put this in your program before it starts doing things:

    return 1 unless $0 eq __FILE__;
    

    __FILE__ is the current source file. $0 is the name of the program being run. If they are the same, your code is being executed as a program. If they're different, it's being loaded as a library.

    That's enough to let you start unit testing the subroutines inside your program.

    require "some/program";
    ...and test...
    

    Next step is to move all the code outside a subroutine into main, then you can do this:

    main() if $0 eq __FILE__;
    

    and now you can test main() just like any other subroutine.

    Once that's done you can start contemplating moving the program's subroutines out into their own real libraries.

提交回复
热议问题