You could do something like this:

my $logger; use constant DEBUGGING => !!$ENV{DEBUG}; sub log_this (&) { DEBUGGING or return; $logger ||= Logger->new; $logger->log($_) for shift->(); } log_this { "Hello world" }; log_this { "Hello", "world" }; log_this { my $data = Expensive->method_call(); "DATA: $data"; };

If the $DEBUG environment variable is false, log_this will return quickly without evaluating the contents of the code block. This still has the overhead of the sub call to log_this itself, but that overhead will be fairly small.

As a bonus, you could use something like Keyword::Simple to alter the parsing of log_this to avoid having even the overhead of that redundant sub call when $DEBUG is false. If you write your custom parser carefully, so that it has no real effect on the syntax of the log_this keyword but just causes it to be no-opped as appropriate, then the custom parsing could be dropped in for a speed-up only on those versions of Perl that support it (5.14+), but it would still work on older Perls.

use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

In reply to Re: Moose based logging question by tobyink
in thread Moose based logging question by jandrew

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.