Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want to keep everything in the same file, why not put the logger at the top in a file scoped lexical.</p> <pre><code>GetOptions( do_logging =&gt; \$do_logging ); my $logerr = $do_logging ? sub {logging_code_here()} : sub {}; </code></pre> <p><code>$logerr</code> is now available in any package defined after that point in the same file.</p> <p>However, it is generally faster to structure your logging calls as follows:</p> <pre><code>my $logerr = sub { logging_code_here() }; $logerr-&gt;("some string $some_var") if $do_logging; </code></pre> <p>that way you avoid a subroutine call and the string argument to $logerr does not need to be calculated if logging is off.</p> <p>You can also setup logging levels:</p> <pre><code>$logerr-&gt;("starting loop") if $do_logging; for (@big_array) { $logerr-&gt;("processing $_") if $do_logging &gt; 1; ... } </code></pre> <p>EDIT: While I don't think its the best practice, based on your comments, here is what you are probably looking for (a pragma):</p> <pre><code>use 5.010; use warnings; use strict; BEGIN { # compile time $INC{'log.pm'}++; # block 'require log;' package log; sub is_active {(caller 1)[10]{log}} # test the hints hash sub import { $^H{log} = 1; # set the hints hash for 'log' my $logmsg = (caller).'::logmsg'; # name of caller's sub no strict 'refs'; *$logmsg = sub {print "logging: @_\n" if is_active} # install sub unless *{$logmsg}{CODE}; # unless we did already } sub unimport { $^H{log} = 0; # unset the hints hash } } package MyPkg; use log; logmsg 'hello, world!'; { no log; logmsg 'nope, not here'; } logmsg 'back again'; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload