Either I was rather clever in the past or, more likely, I had cut-n-pasted code from someone smarter than me, I recently noticed that I am handling a log formatting string in my custom logging function using a hash of subroutine references.

The relevant parts look something like this:

my %meta_char = ( '%' => sub { '%' }, c => sub { $chan }, m => sub { $in_message }, P => sub { $$ }, p => \&_get_package, s => \&_get_subroutine, t => \&_get_timedate, ); ($out_message = $log_format) =~ s/%(.)/$meta_char{$1}->()/ge;

And $out_message is the what gets output.

So if $log_format equals "%t %m", then the time is printed in front of each log message.

The problem is that if $log_format contains a format character that does not exist (for example, "%X") in the %meta_char hash, then Perl does not like that at all.

What I would like is if the code quietly ignored bad log formatting options, but how would I do that? The only thing I can think of is to add some sort of "if exists &sub" logic on the right side of that s// operation. However, Perl is not liking my attempts to do that.

Any other ideas? Thanks much.


In reply to Check exist of anonymous subroutine before calling it within regexp substitute? by jffry

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.