Hi homeveg,

One way to optionally load a module is using stringy eval, which is often abused and can lead to security issues, but can be acceptable with fixed strings:

if ($useGZ) { eval q{ use IO::Compress::Gzip; 1 } or die "IO::Compress::Gzip is NOT available: $@"; print "IO::Compress::Gzip is available\n"; }

Note that since loading of the module is deferred to runtime, there are some side effects: the obvious one is that errors are deferred until runtime, but the possibly more subtle one is that in the case where the module is not loaded, any imports from the module are not available to the entire script, which might lead to compile-time errors. Or worse, hard to detect differences in how Perl interprets your code, for example, in the following, Perl will think that print Dumper $x; is print FILEHANDLE $x;, because it doesn't yet know about the function Dumper(), leading to the confusing warning message "print() on unopened filehandle Dumper". In general, parentheses on optionally imported functions will be required.

eval 'use Data::Dumper; 1' or die $@; print Dumper $x; # WON'T work, confusing warning message print Dumper($x); # will work

Also, you'll have to refer to $GzipError as $IO::Compress::Gzip::GzipError instead, since that variable is also no longer imported at compile time.

Hope this helps,
-- Hauke D

Updates: Added sentence about the interpretation of code and the confusing warning message, and the note on stringy eval.


In reply to Re: error handling by pm initialization by haukex
in thread error handling by pm initialization by homeveg

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.