http://www.perlmonks.org?node_id=693338

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

Most learned monks,

I'm currently working on my port of autodie (a lexical pragma for do-or-die semantics) to Perl 5.8. I've got a rather clever trick that allows me to change how perl resolves subroutines, but I'm starting to hit problems with its scalability.

The trick looks like this:

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

The code above works wonderfully, and maps very well to what I'm doing in autodie when I'm either inserting a subroutine, or deleting a subroutine.

Where it fails is when I'm trying to replace a subroutine that's already there. The reason is that each use of autodie maps to a single BEGIN block, and merging the two middle BEGIN blocks causes the trick to fail:

use strict; open(my $fh, '<', $0); # Calls CORE::open BEGIN { *{main::open} = sub { print "Hi\n"; }; use subs 'open'; } open(my $fh2, '<', $0); # Prints Hi BEGIN { # Deleting and remaking the sub fails! ;( delete $main::{open}; *{main::open} = sub { print "Ho\n"; }; use subs 'open'; } open(my $fh4, '<', $0); # Prints Ho! BEGIN { delete $main::{open}; } open(my $fh5, '<', $0); # Calls CORE::open __END__ Ambiguous use of *{main::open} resolved to *main::open at examples/bla +ck-magic.pl line 17. Subroutine main::open redefined at examples/black-magic.pl line 17. Ho

Unfortunately for me, this means that any operation that needs to replace a subroutine fails, since that involves a delete and an insert. Note that just trying to replace the sub without the magic delete trick doesn't help (Perl never resolves to the first sub declared).

Nesting the BEGIN blocks works fine, but isn't useful for my purposes, since I'm playing with subroutine resolution at every import(), and a BEGIN inside my import() will only run once.

So, does anyone have a trick, that works on Perl 5.8, which allows a subroutine to be replaced with limited scope (as per my first example), but involves only a single BEGIN to do that replacement? This isn't something which comes up every day. ;)

For those interested in learning more about autodie, I've been blogging about it, as well as having made a lightning talk about the idea. The code on CPAN currently works for all my core criteria, but it's the edges cases that are giving me the biggest headaches.

Many many thanks in advance for all your help,