sfink has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to override the builtin time() function with Time::HiRes::time() if Time::HiRes is available. It seems to be more difficult than I expected, perhaps because it is defined as an XS routine? Or perhaps because it is doing special magic through the perl API to override time() itself?

This works:

*gettime = do { eval "use Time::HiRes"; $@ } ? sub { time } : sub { Ti +me::HiRes::time() }; print gettime() . "\n";
But I have to use gettime() instead of time, and I have to use the parentheses. Using a noarg prototype doesn't help. I have tried various combinations of but none of them work.

Is there some way to change the behavior but not the usage of the time() built-in iff the module exists?

Replies are listed 'Best First'.
Re: overriding time() if module exists
by sgifford (Prior) on Nov 08, 2003 at 04:45 UTC
    This works for me:
    BEGIN { eval "use Time::HiRes qw(time);"; }
      Umm... okay, I have no idea how I missed that. Thank you. That works perfectly. I'm going to go hide my face in a closet now.
        No need for the closet. The fact that you need to override built-ins at compile time (or at least before the compilation of the code for which you want the override to work) is not well documented.
Re: overriding time() if module exists
by Anonymous Monk on Nov 08, 2003 at 04:33 UTC
    You don't need use, you don't need those "subs"s.
    *gettime = eval { require Time::HiRes; 1 } ? \&Time::HiRes::time : \&t +ime;