in reply to restore overridden XS methods

It seems that saving and restoring the glob doesn't work, but saving and restoring the CODE entry in the glob works for me:

perl -MTime::HiRes -le "my $x=*Time::HiRes::gettimeofday{CODE};*Time:: +HiRes::gettimeofday = sub(){42};print Time::HiRes::gettimeofday; *Tim +e::HiRes::gettimeofday = $x;print Time::HiRes::gettimeofday"

or, reformatted and untested:

use strict; use Time::HiRes; my $x=*Time::HiRes::gettimeofday{CODE}; *Time::HiRes::gettimeofday = sub(){42}; print "Modified: ", Time::HiRes::gettimeofday,"\n"; *Time::HiRes::gettimeofday = $x; print "Restored: ", Time::HiRes::gettimeofday

Replies are listed 'Best First'.
Re^2: restore overridden XS methods
by bart (Canon) on Mar 01, 2007 at 12:04 UTC
    Under -w, I get:
    Subroutine gettimeofday redefined at z:\test.pl line 6.
    Constant subroutine gettimeofday redefined at z:\test.pl line 8.
    Modified: 42
    Restored: 1172750176936000
    
    So, it works, kinda. With warnings.

    But unfortunately, local does not work:

    #! perl -w use strict; use Time::HiRes; { local *Time::HiRes::gettimeofday{CODE} = sub(){42}; print "Modified: ", Time::HiRes::gettimeofday,"\n"; } print "Restored: ", Time::HiRes::gettimeofday
    This results in the following compile time error:
    Can't modify glob elem in local at z:\test.pl line 5, near "} ="
    Execution of z:\test.pl aborted due to compilation errors.
    

      local works if you use glob assignment syntax:

      { local *Time::HiRes::gettimeofday = sub { print 42; }; print Time::HiRes::gettimeofday(); };; Subroutine Time::HiRes::gettimeofday redefined at (eval 4) line 1, <ST +DIN> line 2. 42 1 print Time::HiRes::gettimeofday();; 1172754765 437500

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
        Clever. The only problem I see is that if there are other variable types attached to the name Time::HiRes::gettimeofday, such as $Time::HiRes::gettimeofday or @Time::HiRes::gettimeofday, that those will be overridden too.

        I don't think it matters for this particular case — or even, in most cases.

Re^2: restore overridden XS methods
by dk (Chaplain) on Mar 01, 2007 at 10:38 UTC
    Aha! It was {CODE} I was missing. Thank you very much and ++ . /me gone reading perlref.