|There's more than one way to do things|
Copy a builtin sub to a different name and then overrideby bliako (Prior)
|on Jun 01, 2018 at 21:43 UTC||Need Help??|
bliako has asked for the wisdom of the Perl Monks concerning the following question:
Hi Monks, I would like to keep track of the total time of sleep() seconds my program got (in main and across ALL modules).
So what I would like to do is to have a counter in my main which initially is set to zero. And override sleep() so that it increments the counter and then sleeps.
I thought it would be easy to copy builtin sleep() to actual_sleep() and then re-implement my own sleep() which will modify the counter AND sleep. Alas it is not ... Here is a short demo:
the result is:
Deep recursion on anonymous subroutine at xx line 7.
How can I make actual_sleep() point to the original sleep() builtin and not, by the looks of it, to the new sleep()?
Update: The eventual solution provided by LanX is not to rename sleep() to actual_sleep() but to use the original sleep() code which resides untouched in CORE even after overriding its alias in CORE::GLOBAL.
a summary of provided solutions from below:
LanX's solution to
simply call CORE::sleep()worked (Re: Copy a builtin sub to a different name and then override) and also worked when sleep() is called from any other package.
beech provided working code based on that (Re: Copy a builtin sub to a different name and then override).
pme made the suggestion to use sleep()'s return value which is the actual seconds slept (Re^3: Copy a builtin sub to a different name and then override).
Useful links: pme suggested reading ex::override which is an easy way to override builtins, alas not "renaming", also CORE. I only had in mind Perl Cookbook's https://docstore.mik.ua/orelly/perl4/cook/ch12_14.htm which also does not mention how to "rename".
Most importantly, the new sleep() will be seen only be those packages whose use follows the BEGIN block with the re-aliased sleep() code. See Re^3: Copy a builtin sub to a different name and then override by BillKSmith.
(in order ot timestamps)
Thanks again. Perl is great.