Re: capturing tcl console for script usage



Thank you for the help, the last proc works just fine with the strings.
Now I'll try to use it with my script.

Bryan Oakley wrote:
pingimbert@xxxxxxxxx wrote:
Thank you for your answer Bryan, I hope it works for my case. Now, this
is what I tried following your suggestion and other posts on similar
issues, I'd appreciate if you or anybody else help me with this:.

rename puts _puts
proc puts {args} {
if {$::do_something_special} {
set args "simon says: $args"
}
_puts $args
}

set msg "hello World\n"
set ::do_something_special 1
puts $msg
set ::do_something_special 0
set msg "bye\n"
puts $msg


And this is what it shows when I run it:

simon says: {hello World
}
{bye
}

Now I'm kind of newbie so if this is a trivial issue, please don't get
mad but, why does it print the braces around my strings? and what
should I do to avoid it?

You see braces because $args is a list. When tcl converts a list to a
string and a list element has special characters it adds braces and/or
backslashes to preserve the "list-ness" of the data.

In the version I posted, the last statement in the new puts command was
"eval _puts $args" rather than just "_puts $args". That "eval" is
important in that it effectively removes one level of braces (that's not
actually what eval does, but that's the net effect in this context).

A true fix is more difficult than just slapping "eval" on the front,
however. You have to realize that puts takes a variable number of
arguments. One convenient fact, though, is that the string to be printed
will always be the last argument. Thus, if you want to modify the string
you must modify only the last element of the $args list.

It goes something like this:

proc puts {args} {
set string [lindex $args end]
set newString "simon sez: $string"
set args [lreplace $args end end $newString]
eval _puts $args
}


--
Bryan Oakley
www.tclscripting.com

.



Relevant Pages