in reply to Defining a subroutine one of two ways depending on whether a package exists
You can do something like this:
This calls Compress::Zlib::crc32 or just returns 0.BEGIN { eval { require Compress::Zlib; import Compress::Zlib 'crc32'; }; *myCRC = $@ ? sub { 0 } # don't have it : sub { crc32(@_) }; }
The way this works is:
The BEGIN block forces this to happen at the very beginning of the program. The eval tries to load the package (in this case Compress::Zlib) and import the symbol 'crc32' into the current package. If this process succeeds, the eval will leave a null string in $@.
The *myCRC = $@ ? sub { } : sub { } part sets up the name 'myCRC' in the symbol table of the current package to refer to one of two subroutines that are defined anonymously here.
In Section
Seekers of Perl Wisdom