Overriding Perl 5 built in functions

ivorw on 2005-08-22T17:02:10

I've been working on Devel::Leak::Object, including the stringification patch which is very useful :) (RT rocks, as does mca).

I had a problem in that I wanted to defer tracking of the bless function until initialisation is complete. I've since discovered that this is not possible - see my post to Perlmonks.

I have gained an understanding of what happens with overrides of built in functions. The crucial point is that these overrides happen at compile time. This means that if you have already used (or required) a module before putting the override in place, it is too late for the override to take effect.

This means that the override also has to be physically first in the script file before the use statements that you want to override, thus:

#!/usr/bin/perl

use strict;
use warnings;

use Foo; # override not in place
use Devel::Leak::Object qw(GLOBAL_bless);
use Bar; # with bless overriden

I also looked at what use subs qw(foo); achieves. What this does is merely a dummy export into its caller's namespace. Once done, a typeglob named foo will exist in the stash, hence will be picked up when parsing barewords. This also affects calls to built ins, which will use the local sub instead. Instead of "use subs", what I needed to do was to export my &bless into other namespaces, as that is what I want to get called.

There is actually no need to do this in my case, as CORE::GLOBAL magic achieves the same results - unless I want to be picky about exactly in which classes I want bless to be overriden.

I might well release this functionality (to allow people to be picky) into Devel::Leak::Object 0.03.