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:
#!/usr/bin/env perl use strict; use warnings; my $total_sleep_time = 0; BEGIN { *actual_sleep = *CORE::GLOBAL::sleep; # ????? *CORE::GLOBAL::sleep = sub { $total_sleep_time+=$_[0]; actual_sleep($_ +[0]) } # << line 7 } # use this module and the other # ... sleep(2); print "total sleep is $total_sleep_time\n";
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()?
Thanks, bliako
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".
Update2:
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.
In reply to Copy a builtin sub to a different name and then override by bliako
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |