My Favorite Modules: diagnostics

One of the things the Perl 5 Porters work hard on is issuing diagnostics that are actually diagnostic. I think they do a pretty good job at this, but sometimes I need a bit more explanation than the typical one-line message.

Now, there is documentation on all of these in perldiag, but paging through that looking for my message is a pain.

Fortunately, there is a module for that: diagnostics. This module causes diagnostics to be expanded into their full explanation as it appears in perldiag.

Typically you would not put a use diagnostics; in your Perl code, though of course you could. Instead, you would load it via a command-line option to perl, or maybe via environment variable PERL5OPT. That is, either

$ perl -Mdiagnostics my-flaky-perl.PL

or

$ env PERL5OPT=-Mdiagnostics perl my-flaky-perl.PL

The environment-variable example is a bit contrived, and U**x specific. It is more useful if you do not run Perl directly, and so can not change the command (if any) used to invoke Perl. In this case you would define the environment variable however it is done in your OS, before starting Perl. If your environment already defines this you will need to add '-Mdiagnostics' to the existing value, space delimited, using the quoting rules of your command shell. Note that this only affects Perls run in the same process that defined PERL5OPT, or in a subprocess of that process.

If for some reason you are unable to inject this module into your Perl, but you can capture your messages from stderr, the splain script will expand them after the fact. See the diagnostics POD for details.

A couple notes on this module:

  • This module was introduced in Perl 5.002.
  • The documentation describes this module as a pragma, which to me means lexical scope. But playing with it seems to say its scope is global.
  • Only the first instance of each diagnostic is expanded.
  • To tie this back to the warnings series, I wrote some Perl to report on what diagnostics are enabled by each warning category. This may involve too much ad-hocery to actually release to CPAN, but the curious can find the code on GitHub.

Previous entries in this series:

Leave a comment

About Tom Wyant

user-pic I blog about Perl.