This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

selective whitespace trimming

Help for those learning Tcl or writing their own scripts.
Post Reply
b
blotter45
Voice
Posts: 17
Joined: Mon Feb 28, 2005 8:37 am

selective whitespace trimming

Post by blotter45 »

heya guys, I'm just looking for a quick way to trim out certain whitespaces from a string. Here is a proc that just takes a seconds input, takes the [duration seconds] value, and trims it down (so weeks becomes w, days becomes d, and so on):

Code: Select all

proc sr:shortdur { t } {
  set t [duration $t]
  regsub -all -- {years?} $t {y} t
  regsub -all -- {weeks?} $t {w} t
  regsub -all -- {days?} $t {d} t
  regsub -all -- {hours?} $t {h} t
  regsub -all -- {minutes?} $t {m} t
  regsub -all -- {seconds?} $t {s} t
  return $t
}
so a duration of "2 weeks 3 days 14 minutes 36 seconds" then becomes "2 w 3 d 14 m 36 s", but then I'd like to trim the spaces between the number and w,d,m,s so that it becomes: "2w 3d 14m 36s".. So is regsub also the best way to do that, or can you recommend another method?
User avatar
demond
Revered One
Posts: 3073
Joined: Sat Jun 12, 2004 9:58 am
Location: San Francisco, CA
Contact:

Post by demond »

use this:

Code: Select all

proc duration {t} {
	set days [expr $t / (3600 * 24)]
	set hour [expr ($t - (3600 * 24 * $days)) / 3600]
	set mins [expr (($t - (3600 * 24 * $days)) % 3600) / 60]
	if $days {append str "$days day(s), "}
	if $hour {append str "$hour hour(s), "}
	return [append str "$mins minute(s)"]
}
connection, sharing, dcc problems? click <here>
before asking for scripting help, read <this>
use

Code: Select all

 tag when posting logs, code
User avatar
De Kus
Revered One
Posts: 1361
Joined: Sun Dec 15, 2002 11:41 am
Location: Germany

Post by De Kus »

why not simply adding the whitespace to the re, if you really love these slow things?

Code: Select all

{ years?}
De Kus
StarZ|De_Kus, De_Kus or DeKus on IRC
Copyright © 2005-2009 by De Kus - published under The MIT License
Love hurts, love strengthens...
b
blotter45
Voice
Posts: 17
Joined: Mon Feb 28, 2005 8:37 am

Post by blotter45 »

De Kus wrote:why not simply adding the whitespace to the re, if you really love these slow things?

Code: Select all

{ years?}
Actually I took your advice and applied it to string map instead of regsub, much better ;)

Code: Select all

proc sr:shortdur { t } {
  set t [duration $t]
  set t [string map {" years" "y" " year" "y"} $t]
  set t [string map {" weeks" "w" " week" "w"} $t]
  set t [string map {" days" "d" " day" "d"} $t]
  set t [string map {" hours" "h" " hour" "h"} $t]
  set t [string map {" minutes" "m" " minute" "m"} $t]
  set t [string map {" seconds" "s" " second" "s"} $t]
  return $t
}
Thanks for the help guys!
Post Reply