Berkeley CSUA MOTD:Entry 13129
Berkeley CSUA MOTD
 
WIKI | FAQ | Tech FAQ
http://csua.com/feed/
2025/04/06 [General] UID:1000 Activity:popular
4/6     

2004/4/10-12 [Computer/SW/Languages/Perl] UID:13129 Activity:nil
4/10    In perl, can I make the program more portable by first checking if
        a module is available, then "use" or "require" it later?
        \_ I think you can do this with an exec call.  Checking.
           no.  i think i was thinking of using an eval block, but i
           can't quite get it to work.
        \_ You can set up a variables using single quoted strings with
           embedded use/require statements and necessary subroutine
           calls and then use eval to figure out which ones work at
           runtime. Here is a short example that returns a hash of @_
           using either MD5 or SHA1 (which ever is found first, unless
           a search order is specified via $MODE):

        sub doHash
        {
           my $hashCmdMD5 = 'use Digest::MD5 qw(md5 md5_hex md5_base64);';
           $hashCmdMD5 .= " md5_hex('@_'); ";

           my $hashCmdSHA1 = 'use Digest::SHA1 qw(sha1 sha1_hex sha1_base64);';
           $hashCmdSHA1 .= " sha1_hex('@_'); ";

           my $hashCmd = ($MODE eq "MD5" ? $hashCmdMD5 : $hashCmdSHA1);
           my $hash = eval $hashCmd;

           if ($@ || !defined($hash) || $hash eq "") {
              $hashCmd = ($MODE eq "MD5" ? $hashCmdSHA1 : $hashCmdMD5);
              $hash = eval $hashCmd;
           }

           return ($@ || !defined($hash) ? "" : $hash);
        }
        \_ nice.  where's that code from?  yours?
           \_ This is modified from some code I wrote for work. I added
              $MODE for this example, so that one can get an idea about
              how this can work.