http://qs1969.pair.com?node_id=1132828

perl_help26 has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

I have a .pl script with the following structure:

use X; use Data::Dumper; sub func1 {....} sub func2 {....} until (should_stop()) { ..... .... .. }
I am trying to build a test module for this pl script. Is there a way to export the functions WITHOUT running the while loop? Preferably, I do not want to split the functions into a .pm file. Thanks ...

Replies are listed 'Best First'.
Re: Test automation
by Eily (Monsignor) on Jul 01, 2015 at 14:38 UTC

    You can do something like this:

    sub main { until (should_stop()) { # code goes here } } main unless caller;
    This way the main sub will be called only if the script is called directly and not if it is included in a test through require "script.pl".

      Suppose we are running the script from crontab, will that be considered as a caller?

        caller only knows about callers in the same perl process. So do or require will not trigger a main call, while cron, or even system "perl script.pl"; will.

Re: Testing a .pl script
by Monk::Thomas (Friar) on Jul 01, 2015 at 14:40 UTC
Re: Test automation
by Corion (Patriarch) on Jul 01, 2015 at 14:29 UTC

    Maybe define/override the function should_stop so it always returns false?

      I like that. So I should put something like this in my test.pl?
      local *should_stop = sub { return 1; }; require ('wrong_settings_detection.pl');
      Also,suppose i change my code to:
      package X; sub func1 {....} sub func2 {....} until (should_stop()){...}
      Can i export the package into my test.pl ???

        You can still override the things:

        package X; use strict; use Exporter 'import'; use vars '@EXPORT_OK'; @EXPORT_OK = qw(func1 func2 ); sub func1 { ... }; sub func2 { ... }; sub should_stop { ... }; until (should_stop()){...}

        And then in your test file:

        local *X::should_stop = sub { return 1 }; require X; X->import('func1');
Re: Testing a .pl script
by Discipulus (Canon) on Jul 01, 2015 at 20:02 UTC
Re: Testing a .pl script
by Anonymous Monk on Jul 01, 2015 at 17:47 UTC
    'Preferably, I do not want to split the functions into a .pm file.'

    But that is precisely what you should do.