Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.
  • This is

    "   a      spacey      string    "
    It's easy to quibble about readability with trivivial examples. But a "readable" language often implies "limited in power" too. So how would you solve the same problem with the added requirement that multiple spaces should be squashed into a single space? In Perl it's easy: you just have to add the additional statement:

    tr/ //s;

    s/\s+/ /g;
    (Too bad tr doesn't recognize the \s meta character class.)

    So how do you tackle that in a readable language like Python? I don't know enough Python, let's stick to something I do know: PL/SQL, the (Ada-based) language Oracle includes in its databases:

    function normalize_spaces(s in varchar2) return varchar2 is
      r varchar2(32000);
      r := trim(s);
      while(instr(r, '  ') > 0) loop
        r := replace(r, '  ', ' ');
      end loop;
      return r;
    That's what "readability" buys you: a requirement for a lot of extra, very low level code. But, it least it's "readable"!

    I wouldn't be too surprised that in general, Python makes you jump through the same hoops, as Guido is notorious for ripping out features out of the language he considers too advanced.

    p.s. I like Javascript, and their solution really appeals to me:

    function normalize_space(s) {
      return s.replace(/^\s+/, '').replace(/\s+$/, '').replace(/\s+/g, ' ');
    I really like chaining in this way. Much better than the nesting of procedural function calls that you have to write backwards — the last function to call is the first one you read in the source. And Javascript knows first class regular expressions (which are like qr// objects in Perl).