Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Using delete package::{subroutine} to change resolution of subroutines

by ikegami (Patriarch)
on Jun 22, 2008 at 06:56 UTC ( [id://693342]=note: print w/replies, xml ) Need Help??


in reply to Using delete package::{subroutine} to change resolution of subroutines

Two problems.

  • First, as the warning indicates, the main::open in

    *{main::open} = sub { print "Ho\n"; };

    is interpreted as a call to open. (Upd: Not sure how it's being interpreted anymore, but it's definitely not working as expected. ) You want

    my $glob_ref = do { no strict 'refs'; \*{'main::open'} }; *$glob_ref = sub { print "Ho\n"; };
  • Second, you delude yourself by putting the use subs at the bottom.

    BEGIN { # Deleting and remaking the sub fails! ;( delete $main::{open}; *{main::open} = sub { print "Ho\n"; }; use subs 'open'; }

    means

    BEGIN { # Deleting and remaking the sub fails! ;( delete $main::{open}; *{main::open} = sub { print "Ho\n"; }; BEGIN { require subs; import subs 'open'; } }

    which is compiled and executed as follows:

    1. "delete $main::{open};" is compiled.
    2. "*{main::open} = sub { print "Ho\n"; };" is compiled.
    3. "require subs;" is compiled.
    4. "import subs 'open';" is compiled.
    5. "require subs;" is executed. (The inner BEGIN is executed as soon as it's compiled.)
    6. "import subs 'open';" is executed.
    7. "delete $main::{open};" is executed. (The outer BEGIN is executed as soon as it's compiled.)
    8. "*{main::open} = sub { print "Ho\n"; };" is executed.

    "import subs 'open';" should not be executed before "delete $main::{open};".

Fixed:

use strict; use warnings; use subs qw( ); open(my $fh, '<', $0); # Calls CORE::open BEGIN { my $glob = do { no strict 'refs'; \*{'main::open'} }; *$glob = sub { print "Hi\n"; }; import subs 'open'; } open(my $fh2, '<', $0); # Prints Hi BEGIN { delete $main::{open}; my $glob = do { no strict 'refs'; \*{'main::open'} }; *$glob = sub { print "Ho\n"; }; import subs 'open'; } open(my $fh4, '<', $0); # Prints Ho BEGIN { delete $main::{open}; } open(my $fh5, '<', $0); # Calls CORE::open

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://693342]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2024-06-21 12:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.