Overloading Constants
You can change how constants are interpreted by Perl
with overload::constant
, which is most usefully
placed in a package's import
method. (If you do
this, you should properly invoke
overload::remove_constant
in the package's
unimport
method so that the package can clean up
after itself when you ask it to.)
Both overload::constant
and
overload::remove_constant
expect a list of
key/value pairs. The keys should be any of integer
,
float
, binary
,
q
, and qr
, and each value should
be the name of a subroutine, an anonymous subroutine, or a code
reference that will handle the constants.
sub import { overload::constant ( integer => \&integer_handler, float => \&float_handler, binary => \&base_handler, q => \&string_handler, qr => \®ex_handler ) }
Any handlers you provide for integer
and
float
will be invoked whenever the Perl tokener
encounters a constant number. This is independent of the use
constant
pragma; simple statements such as
$year = cube(12) + 1; # integer $pi = 3.14159265358979; # float
will trigger whatever handler you requested.
The binary
key lets you intercept binary,
octal, and hexadecimal constants. q
handles
single-quoted strings (including strings introduced with
q
) and constant substrings within
qq
- and qx
-quoted strings and
here documents. Finally, qr
handles constant pieces
within regular expressions, as described at the end of Chapter 5.
The handler will be passed three arguments. The first argument is the original constant, in whatever form it ...
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.