sub Cmp_string { #get the object my \$a = shift; #figure out what sign to put between the real # and imaginary part. I do this so we don't get # something like '3 + -5I', although it fairly # irrelevant my \$sign = (\$a->Imag > 0) ? " + " : " - "; #return a string that looks like '3 - 5I' return \$a->Real.\$sign.abs(\$a->Imag)."I"; } sub Cmp_add { #get the calling object; \$a is always the Complex object, it # does not matter if we call '\$x + 2' or '2 + \$x' or # '\$x + \$y' ... this \$a will always be \$x. my \$a = shift; #get the second object, either a number or an object my \$b = shift; #if \$b is not a Complex object do the simple math unless( \$b->isa( 'Complex' ) ) { #return a new Complex object after doing the simple # arithmetic return new Complex( \$a->Real + \$b, \$a->Imag ); } #return a new Complex object after doing the 'complex' # arithmetic return new Complex(\$a->Real+\$b->Real, \$a->Imag+\$b->Imag); } sub Cmp_multiply { #get the calling object; \$a is always the Complex object, it # does not matter if we call '\$x * 2' or '2 * \$x' or # '\$x * \$y' ... this \$a will always be \$x. my \$a = shift; #get the second object, either a number or an object my \$b = shift; unless( \$b->isa( 'Complex' ) ) { #return a new Complex object after doing the simple # arithmetic return new Complex( \$a->Real * \$b, \$a->Imag * \$b); } #figure out the new real and imaginary parts. Good'ol # FOIL method anybody? my \$real = (\$a->Real * \$b->Real) + (\$a->Imag * \$b->Imag * -1); my \$imag = (\$a->Real * \$b->Imag) + (\$a->Imag * \$b->Real); #return a new Complex object after doing the 'complex' # arithmetic return new Complex(\$real, \$imag); }