[PATCH] Add .trim method

[email protected] (Ovid) Sun, 11 Jan 2009 16:17:36 -0800 (PST)
Newsgroups perl.perl6.internals
Message-ID <[email protected]>
This is an update to my last patch (which you may not see because I sent it from the wrong email address).  Here are my updated notes:

This patch implements the .trim() method for strings.

Problem:   I don't like the magic number '32

  not_whitespace = is_cclass 32, s, start

But I couldn't figure this out:

  $I0 = is_cclass .CCLASS_WHITESPACE, target, pos

I
was getting an 'unknown parrot op' or something like that (too tired to
recompile and find out the exact error message).  I can't figure out
how to get parrot to recognize that.

Many thanks to moritz++ for handholding on IRC.

Oh, there are no tests because I couldn't find any pugs tests for this :( What's the appropriate procedure for this?  However, all tests pass and a small test program passed (including calling trim() as a function).

 
Cheers,
Ovid
--
Buy the book         - http://www.oreilly.com/catalog/perlhks/
Tech blog            - http://use.perl.org/~Ovid/journal/
Twitter              - http://twitter.com/OvidPerl
Official Perl 6 Wiki - http://www.perlfoundation.org/perl6
trim.patch (application/octet-stream, 1.3 KB)
Index: languages/perl6/src/builtins/any-str.pir
===================================================================
--- languages/perl6/src/builtins/any-str.pir	(revision 35423)
+++ languages/perl6/src/builtins/any-str.pir	(working copy)
@@ -21,7 +21,7 @@
 .namespace []
 .sub 'onload' :anon :init :load
     $P0 = get_hll_namespace ['Any']
-    '!EXPORT'('capitalize,chop,chomp,chars,:d,:e,:f,index,lc,lcfirst,rindex,ord,substr,uc,ucfirst,unpack', 'from'=>$P0)
+    '!EXPORT'('capitalize,chop,chomp,chars,:d,:e,:f,index,lc,lcfirst,rindex,ord,substr,trim,uc,ucfirst,unpack', 'from'=>$P0)
 .end
 
 
@@ -128,6 +128,39 @@
        .return (retv)
 .end
 
+=item trim()
+
+Remove leading and trailing whitespace from a string.
+
+=cut
+
+.sub 'trim' :method :multi(_)
+    .local string s
+    .local int start, end, temp, len
+    .local int is_whitespace
+    s = self
+    start = 0
+    end = length s
+    if end == 0 goto donetail
+  loop:
+    is_whitespace = is_cclass 32, s, start
+    unless is_whitespace goto done
+    inc start
+    goto loop
+  done:
+    temp = end
+  tail:
+    dec temp
+    is_whitespace = is_cclass 32, s, temp
+    unless is_whitespace goto donetail
+    end = temp
+    goto tail
+  donetail:
+    len = end - start
+    s = substr s, start, len
+    .return(s)
+.end
+
 =item comb()
 
 Partial implementation for now, returns a list of strings