diff --git a/src/core/Str.pm b/src/core/Str.pm index b55c9cee6d2..4c5a18400a7 100644 --- a/src/core/Str.pm +++ b/src/core/Str.pm @@ -404,6 +404,23 @@ my class Str does Stringy { ); self.substr($pos); } + + + method trim-trailing(Str:D:) { + my Int $pos = self.chars - 1; + --$pos while $pos >= 0 && nqp::p6bool( + nqp::iscclass( + pir::const::CCLASS_WHITESPACE, + nqp::unbox_s(self), + nqp::unbox_i($pos) + ) + ); + $pos < 0 ?? '' !! self.substr(0, $pos + 1); + } + + method trim(Str:D:) { + self.trim-leading.trim-trailing; + } } @@ -471,3 +488,8 @@ multi sub ords(Str $s) { my str $ns = nqp::unbox_s($s); (^$c).map: { nqp::p6box_i(nqp::ord(nqp::substr($ns, $_, 1))) } } + +# TODO: Cool variants +sub trim (Str:D $s) { $s.trim } +sub trim-leading (Str:D $s) { $s.trim-leading } +sub trim-trailing(Str:D $s) { $s.trim-trailing } diff --git a/t/spectest.data b/t/spectest.data index bf15fc54aa4..31d46dc5594 100644 --- a/t/spectest.data +++ b/t/spectest.data @@ -560,7 +560,7 @@ S32-str/samecase.t # icu S32-str/split.t S32-str/sprintf.t # S32-str/substr.t # err: Method 'capitalize' not found for invocant of class 'Str' -# S32-str/trim.t # err: Could not find sub &trim +S32-str/trim.t S32-str/uc.t # icu S32-str/ucfirst.t # icu # S32-str/unpack.t # err: Default constructor only takes named arguments