Beefy Boxes and Bandwidth Generously Provided by pair Networks Bob
Syntactic Confectionery Delight
 
PerlMonks  

Answer: Defining a subroutine one of two ways depending on whether a package exists

( #86671=categorized answer: print w/ replies, xml ) Need Help??

Q&A > subroutines > Defining a subroutine one of two ways depending on whether a package exists contributed by bikeNomad

You can do something like this:

BEGIN { eval { require Compress::Zlib; import Compress::Zlib 'crc32'; }; *myCRC = $@ ? sub { 0 } # don't have it : sub { crc32(@_) }; }
This calls Compress::Zlib::crc32 or just returns 0.

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.

Comment on Answer: Defining a subroutine one of two ways depending on whether a package exists
Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (14)
As of 2014-04-23 22:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (556 votes), past polls