A Pike module and a Roxen tag

When you’r used to one programming language and start learning a new one you sometimes miss some features from the former. That happened to me a couple of years ago when we started using Roxen at work. What I missed was the trim functions from PHP. Sure, Pike and RXML can trim strings from whitespace but the beauty of trim, trim and trim in PHP is that you can trim characters as well as whitespace. And to my knowledge there’s no equivalent to trim and trim – that is only trim the left and right side respectively of the string.

So I wrote a Pike module that did that and also created an RXML tag of it. Just yesterday I rewrote that code since I do think I’ve become a better programmer and have come to learn Pike a lot better since my first try.

And I also wrote a method to shorten a string from the center and out, i.e. trim.

So here are some examples of usage:

12 lines of Pike
  1. import .trim;
  2. string path = “/this/is/a/path/”;
  3. write(“%s\\n”, rtrim(path, “/”));
  4. // Will output: /this/is/a/path
  5. write(“%s\\n”, trim(path, “/”));
  6. // Will output: this/is/a/path
  7. string long_str = “This is some string that’s too long for us”;
  8. write(“%s\\n”, ctrim(long_str, 20));
  9. // Will output: This is…for us

And here’s the RXML implementation:

5 lines of RoXen Macro Language
  1. <trim right=“” char=“/”>/this/is/a/path/</trim>
  2. <!– /this/is/a/path –>
  3. <trim center=“” length=“20”>This is some string thats too long for us</trim>
  4. <!– This is…for us –>

And that’s that.

Trim Pike module 17:31, Sat 17 October 2009 :: 4 kB
Trim Roxen tag module 17:31, Sat 17 October 2009 :: 4.8 kB