Mark Fowler mark at
Wed May 1 16:40:02 BST 2013

On Wednesday, 1 May 2013 at 11:06, Th. J. van Hoesel wrote:
> However, can someone point me out what is happening between lines 132 and 144 of ? This part is the neatest part of the module, where it enables the module to use constants in your Perl programs.

Nothing too complicated.  Let's reformat this:

my %_const_handlers =
(q => sub { return __PACKAGE__->new($_[0]) || $_[1] });

To this:

my $subroutine_ref = sub {
  my $string_value_of_source = shift;
  my $scalar_containing_value = shift;

  # attempt to create a number fraction
  my $number_fraction = Number::Fraction->new(

  # if we could create a number fraction out of it
  # i.e. the constructor returned something 'true'
  # then return that
  if ($number_fraction) {
    return $number_fraction

  # must have been a constant that number fraction can't handle,
  # i.e. a string like "foo" or "bar" that isn't a number fraction
  # just return the second argument to this function which is a
  # scalar representing how perl has interpreted the source
  return $scalar_containing_value

# prepare additional arguments we'll pass to overload later
# at import time if they used ":constant"
my %_const_handlers = (
  'q' => $subroutine_ref


Which makes it clear what this is doing:

sub import {
  overload::constant %_const_handlers if $_[1] and $_[1] eq ':constants';

It's doing the constant overloading if and only if someone wrote

  use Number::Fraction qw(:constants)



More information about the mailing list