### Perfect Division

by acid06 (Friar)
 on Sep 09, 2001 at 12:34 UTC 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)}; } 1; ```
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"

Create A New User
Node Status?
node history
Node Type: sourcecode [id://111259]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2017-06-28 10:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How many monitors do you use while coding?

Results (631 votes). Check out past polls.