Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Perfect Division

by acid06 (Friar)
on Sep 09, 2001 at 12:34 UTC ( #111259=sourcecode: print w/replies, xml ) Need Help??
Category: Fun Stuff
Author/Contact Info acid06
Description: I was reading some fun stuff here and couldn't resist when I read this part of the message:
"11. Let's say the program you're writing may possibly try to divide by zero. If this exception occurs, how should your program cope?
b) Redefine the laws of mathematics so that any number divided by zero is equal to 42. Problem solved."

So... here it is. All you have to do is save it and use PerfectDivision;

Note: it doesn't work unless you provide the values on compile time, so you can't do stuff like print $ARGV[0]/0; without getting the Illegal division by zero error.
update: corrected a bug which prevented it from working properly
#!/usr/bin/perl -w
package PerfectDivision;
use strict;

use overload 
    nomethod    =>    \&wrap,
    '/'            =>    sub    {
                        my ($a, $b) = @_;
                        return 42 if "$b" eq "0";
                        eval("return $a / $b")
    '""'        =>    \&stringify,
    '0+'        =>    \&numify;

sub new {
    my $class    = shift;
    my $number    = shift;
    bless \$number, $class;

sub stringify { "${$_[0]}" }
sub numify { 0 + "${$_[0]}" }

sub wrap {
    my ($val1, $val2, $inv, $meth) = @_;
    ($val1, $val2) = ($val2, $val1) if $inv;
    eval("return $val1 $meth $val2;");

sub import {
    overload::constant integer => sub {PerfectDivision->new(shift)};

Replies are listed 'Best First'.
Re: Perfect Division
by liverpole (Monsignor) on Feb 06, 2006 at 13:34 UTC
    This is terrific++ Not just further proof that 42 really is the answer to everything, but a neat introduction to use overload.

    @ARGV=split//,"/:L"; map{print substr crypt($_,ord pop),2,3}qw"PerlyouC READPIPE provides"

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: sourcecode [id://111259]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2020-09-30 07:27 GMT
Find Nodes?
    Voting Booth?
    If at first I donít succeed, I Ö

    Results (160 votes). Check out past polls.