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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |