Perl-like split proc

Clovertech Forums Read Only Archives Cloverleaf Tcl Library Perl-like split proc

  • Creator
    Topic
  • #49982
    Kevin Kinnell
    Participant

      This is a partial emulation of the Perl ‘split’ funckerator (not the wimpy little Tcl split command.)   Since Tcl also lacks quoterators it’s a bit more difficult to get regexes right, but they are still useful, and I use them all the time.

      This is a good proc for dividing up a message into logically related chunks, as long as you don’t have to deal with ‘{‘ characters somewhere in the message.

      One way I’ve used it, for example, is to parse messages into ‘everything before the first obx group’, a list of ‘obx groups’ (an obx plus associated nte’s, e.g.), and ‘everything after & including the the last obx’–for the problem at hand it was a very fast and low-line-count-code solution.  The regex for that one is {r(?=OBX|)}.

      It’s handy enough to keep lying on the workbench within easy reach, though to keep things clean I actually keep it in a namespace and declare chunks as a variable.

      Code:

         # proc regsplit
         # Kevin Kinnell — 2007
         # (use at your own risk!)
         # Splits $str into a list on $rgx, removes the
         # matches, returns the resulting list.

         # This proc does NOT “clean up” the string being operated
         # on.  It uses the Tcl string-is-a-list convention to return its
         # list, NOT the list command.

         proc regsplit { rgx str } {
            set chunks {}
            regsub -all $rgx $str “} {” chunks
            return [cconcat “{{” $chunks “}}”]
         }

    • The forum ‘Tcl Library’ is closed to new topics and replies.