Next Tricks of the Wizards 146

Overloading: Example

        sub dotproduct {
          my ($vec1, $vec2, $rev) = @_;
          if (ref $vec2 && $vec2->isa('Vector3')) {
            my $dp = 0;
            for (qw(X Y Z)) {
              $dp += $vec1->{$_} * $vec2->{$_};
            }
            return $dp;
          } elsif (! defined ref $vec2) {   # It's a scalar
            return $vec1->new(map {$vec2 * $vec1->{$_}} qw(X Y Z));
          } else {
            croak "Invalid vector scalar multiplication";
          }
        }
        sub crossproduct { 
           ...
        }


Next Copyright © 2003 M. J. Dominus