Professional Perl | 7
[previous] |
Professional Perl
Overriding Built-in Functions
Another way to predeclare subroutines is with the use subs pragma. This not only predeclares the subroutine, but also allows us to override Perl's existing built-in functions and replace them with our own. We can access the original built-in function with the CORE:: prefix. For example, here is a replacement version of the srand function, covered in Chapter 34, which issues a warning if we use srand in a version of Perl of 5.004 or greater without arguments:
#!/usr/bin/perl
# srandcall.pl
use warnings;
use strict;
use subs qw(srand);
sub srand {
if ($] >= 5.004 and not @_) {
warn "Unqualified call to srand redundant in Perl $]";
} else {
# call the real srand via the CORE package
CORE::srand @_;
}
}
Now if we use srand without an argument and the version of Perl is 5.004 or greater, we get a warning. If we supply an argument we're assumed to know what we are doing and are supplying a suitably random value.
Subroutines like this are generally useful in more than one program, so we might want to put this definition into a separate module and use it whenever we want to override the default srand:
#!/usr/bin/perl
# mysrand.pm
package mysrand;
use strict;
use vars qw(@ISA @EXPORT @EXPORT_OK);
use Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(mysrand);
@EXPORT_OK = qw(srand);
sub mysrand {
if ($] >= 5.004 and not @_) {
warn "Unqualified call to srand redundant in Perl $]";
} else {
# call the real srand via the CORE package
CORE::srand @_;
}
}
use subs qw(srand);
sub srand {&mysrand;}; # pass @_ directly to mysrand
This module, which we would keep in a file called mysrand.pm to match the package name, exports the function mysrand automatically, and the overriding srand function only if we ask for it. use mysrand; # import 'mysrand' use mysrand qw(mysrand); # import and predeclare mysrand; use mysrand qw(srand); # override 'srand'
We'll talk about packages, modules, and exporting subroutines in Chapter 10.
[previous] |
Created: March 8, 2001
Revised: March 8, 2001