Next Tricks of the Wizards 153

Overloading: Y2K Detection Example

        { my ($year, $arg);
          %methods = (
             '+' => sub { $year + $arg },
             '%' => sub { $year % $arg },
            'r%' => sub { $arg % $year },
             ...
          );
          sub default {
            my ($y2k, $a, $rev, $op) = @_;
            my $code = $rev 
              ? ($methods{"r$op"} || $methods{$op}) 
              :                      $methods{$op}
              ;
            croak "No method defined for y2k object for operation `$op'"
              unless $code;
            $arg = $a;
            $year = $y2k->{YEAR};
            &$code;        
          }
        }


Next Copyright © 2003 M. J. Dominus