Overriding Built-in Functions

Many built-in functions may be overridden, although (like knocking holes in your walls) you should do this only occasionally and for good reason. Typically, this might be done by a package attempting to emulate missing built-in functionality on a non-Unix system. (Do not confuse overriding with overloading, which adds additional object-oriented meanings to built-in operators, but doesn't override much of anything. See the discussion of the overload module in Chapter 13 for more on that.)

Overriding may be done only by importing the name from a module--ordinary predeclaration isn't good enough. To be perfectly forthcoming, it's the assignment of a code reference to a typeglob that triggers the override, as in *open = \&myopen. Furthermore, the assignment must occur in some other package; this makes accidental overriding through typeglob aliasing intentionally difficult. However, if you really want to do your own overriding, don't despair, because the subs pragma lets you predeclare subroutines via the import syntax, so those names then override the built-in ones:

use subs qw(chdir chroot chmod chown);
chdir $somewhere;
sub chdir { … }

In general, modules should not export built-in names like open or chdir as part of their default @EXPORT list, since these names may sneak into someone else's namespace and change the semantics unexpectedly. If the module includes the name in the @EXPORT_OK list instead, importers will be forced to explicitly request ...

Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.