Re: Bests way to handle lines in files with only a return character?



slebetman@xxxxxxxxx wrote:
This way you also handle lines containing spacebars and tabs. It's also
easy to handle coments in the file in a similar fashion:
  set commentChar "//"
  set n [string first $commentChar $line]
  if {$n != -1} {
    set line [string range $line $n end]
  }
  set line [string trim $line]

Hmm, as someone who likes REs I'd be tempted to replace those lines above with this:

  set line [string trim [regsub {//.*} $line {}]]

But then there's the whole issue of quoting (what if you want to retain
the comment character?) It's usually easier to only allow comments to be
"whole line" comments, resulting in cleanup code like this:

  set line [regsub {^//.*} [string trim $line] {}]

Though if you're processing lines in a loop, it's actually more common
to do this:

  foreach line $theData {
     set line [string trim $line]
     if {[string match //* $line]} continue  ;# No comment lines
     if {$line eq ""}              continue  ;# No blank lines
     # Process line here...
  }

There are probably as many variations on this as there are Tclers. :-)

Donal.
.



Relevant Pages

  • Re: How can I ensure that I always have a list?
    ... set contentsList [string trim $contentsList] ... then never perform string transformations on the ... set cannotOpenFile [catch { ... It appears you are dealing with XML -- STOP, ...
    (comp.lang.tcl)
  • Re: How can I ensure that I always have a list?
    ... set contentsList [string trim $contentsList] ... then never perform string transformations on the ... with string commands it will always remain a list and can contain any ... set cannotOpenFile [catch { ...
    (comp.lang.tcl)
  • Re: How can I ensure that I always have a list?
    ... set contentsList [string trim $contentsList] ... then never perform string transformations on the ... set cannotOpenFile [catch { ... Do not attempt to parse the XML yourself, you will make mistakes (as evidenced by your post. ...
    (comp.lang.tcl)
  • Re: remove new line in constant
    ... That's not a valid string - \d isn't a valid escape sequence. ... > I use string trim but it doesn't work. ... That won't compile either, for various reasons. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: beginner question
    ... Returns a value equal to string except that any leading or trailing ... characters from the set given by chars are removed. ... % string trim $str abc ... abc def 123 ...
    (comp.lang.tcl)