Skip to content

Instantly share code, notes, and snippets.

@usev6
Created January 29, 2015 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usev6/19baafe3390a274d87d0 to your computer and use it in GitHub Desktop.
Save usev6/19baafe3390a274d87d0 to your computer and use it in GitHub Desktop.
Attempt to make subst-mutate work on variables of type Numeric
$ cat subst-mutate-numeric.t
use v6;
use Test;
plan 10;
my $foo = 70;
my $match = $foo.subst-mutate(7, 2);
is $foo, 20, 'can use subst-mutate with variable of type Int';
is $match.Str, 7, 'matched text is correct';
isa_ok $foo, Str, 'type changed to Str after applying method subst-mutate';
$foo = 2/5;
$match = $foo.subst-mutate(2, 3);
is $foo, 0.4, 'can use subst-mutate with variable of type Rat';
isa_ok $match, Any, 'no match returned';
isa_ok $foo, Str, 'type changed to Str after applying method subst-mutate';
$foo = 2/5;
$match = $foo.subst-mutate(4, 6);
is $foo, 0.6, 'substition happens after stringification (1)';
is $match.Str, 4, 'matched text is correct';
$foo = pi;
$match = $foo.subst-mutate(3, 4, :g);
is $foo, 4.14159265458979, 'substition happens after stringification (2)';
is $match.Str, '3 3', 'matched text is correct';
done;
@usev6
Copy link
Author

usev6 commented Jan 29, 2015

And the corresponding change to src/core/Cool.pm (naive approach):

$ git diff
diff --git a/src/core/Cool.pm b/src/core/Cool.pm
index 337bbfd..d362b1c 100644
--- a/src/core/Cool.pm
+++ b/src/core/Cool.pm
@@ -207,6 +207,15 @@ my class Cool { # declared in BOOTSTRAP
         $/ := nqp::getlexdyn('$/');
         {*}
     }
+    multi method subst-mutate(Numeric:D $self is rw: $matcher, $replacement,
+                       :$SET_CALLER_DOLLAR_SLASH, *%options) {
+        $/ := nqp::getlexdyn('$/');
+        my $self_stringified = $self.Stringy;
+        my $match = $self_stringified.subst-mutate($matcher, $replacement,
+                       :$SET_CALLER_DOLLAR_SLASH, |%options);
+        $self = $self_stringified;
+        return $match;
+    }

     proto method IO(|) { * }
     multi method IO(|c) { IO::Path.new(self) }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment