Subject: | * could be overloaded to handle scalar multiplication, too |
The overloading of * could be changed to handle both matrix and scalar multiplication. You just have to check the third argument of the subroutine, it's 1 when the multiplicand is not an object, so the second one must be. Patch and simple example attached.
Subject: | example.pl |
#!/usr/bin/perl
use warnings;
use strict;
use Math::Matrix;
my $m1 = 'Math::Matrix'->new([1, 2, 3],
[4, 5, 6],
[7, 8, 9]);
print $m1 * 2;
print 2 * $m1;
print $m1 * $m1;
Subject: | math-matrix.patch |
diff --git a/lib/perl5/Math/Matrix.pm b/lib/perl5/Math/Matrix.pm
index 0105845..809de5f 100644
--- a/lib/perl5/Math/Matrix.pm
+++ b/lib/perl5/Math/Matrix.pm
@@ -247,7 +247,7 @@ use overload
'~' => 'transpose',
'+' => 'add',
'-' => 'subtract',
- '*' => 'multiply',
+ '*' => '_clever_multiply',
'""' => 'as_string';
sub version {
@@ -444,6 +444,15 @@ sub vekpro {
$result;
}
+sub _clever_multiply {
+ my ($m1, $m2, $first_not_matrix) = @_;
+ if ($first_not_matrix || ! ref $m2) {
+ return $m1->multiply_scalar($m2)
+ } else {
+ return $m1->multiply($m1)
+ }
+}
+
sub multiply {
my $self = shift;
my $class = ref($self);