in reply to Best practice for handling subroutines that are conditionally loaded?

There must be information missing...

...if the tests are all at one place, why not put them inside the same conditional if ($ENV{MYMOD_DEBUG_LEVEL}){...} ?

Even better why don't you refactor the tests into a separate module which is used if ?

You could even put the essential use Module there as long as you run it inside the same package

Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^2: Best practice for handling subroutines that are conditionally loaded?
by nysus (Parson) on Mar 08, 2024 at 15:08 UTC

    My modules may have debug code sprinkled in:

    package Some::Useful::Module; sub my_mod_func { my ($self) = @_ dd $self; }

    So I want to conditionally load my debug code for this module.

    $PM = "Perl Monk's";
    $MC = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate Priest Vicar Parson";
    $nysus = $PM . ' ' . $MC;
    Click here if you love Perl Monks

      Either unsprinkle them or generate the empty function stubs automatically inside a BEGIN block.¹

      Having code all over the place calling "Schrödinger" functions doesn't strike me as a good design decision.

      The next maintainer might lock you in a box with randomly activated poison. ;)

      Update

      ¹) something like BEGIN { *{$_} = sub {} for @imports }

      NB: you can reuse @imports for your use if to keep it DRY

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      see Wikisyntax for the Monastery

        These are modules for my own use that are in alpha or beta stages and undergo frequent changes. Sprinkling and unsprinkling in debug code sucks. This way I can just leave it in for a few months. After the module matures enough, and surely if I'm going to share it, I would then "unsprinkle" these calls.

        $PM = "Perl Monk's";
        $MC = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate Priest Vicar Parson";
        $nysus = $PM . ' ' . $MC;
        Click here if you love Perl Monks

        Your snippet is pretty slick. But I could not get it to work when loaded from an outside module so I could avoid boilerplate. You can see my comment below for the solution I ended up implementing. Thanks for your help with this and suggestions.

        $PM = "Perl Monk's";
        $MC = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate Priest Vicar Parson";
        $nysus = $PM . ' ' . $MC;
        Click here if you love Perl Monks