Aug 232013

Very often from TCL scripts we may want to execute external commands.
But not always they also available, sometime the command that we want to execute may not exist on the respective machine.
One solution is to put the exec command in a catch { exect $your_command $arg1 $arg2 ... } and then to check if it was successfully.

The problem here is that you have to write few lines of code to check if the command is missing, or the arguments passed were wrong.

Other solution, more elegant I think, is to use auto_execok procedure to check if your command really exists, something like bellow:

% set ls_cmd_path [auto_execok ls]
% puts $ls_cmd_path
% set ls_cmd_path [auto_execok ls_wrong]
% puts $ls_cmd_path 


So, just call the set result [auto_execok $your_command]  and check if the result is not empty string to see if the command really exists.


Sep 082012

Few time ago I had a tcl chalange that in other languages is straight forward: split a string using as separator a substring.
In tcl there is a split function: [split $myStr $subStr] but, by default it splits by any char of $subStr.
To be more precise let's assume that we have a string $my_str like

"set1 line1
set1 line 2
set 1 line 3

set2 line 1
set2 line 2

set3 line1
set3 line2
set3 line3"

and we want to split by empty line ("\n\n").

If we try soemething like
set list_str [split $my_str "\n\n"]
the $list_str is
{set1 line1 } {set1 line 2} {set 1 line 3} {} {set2 line 1} {set2 line 2} {} {set3 line1} {set3 line2} {set3 line3}
it is the same thing as set list_str [split $my_str "\n"] .

The trick is to replace the "\n\n" sequence in $my_str with one single char , a char which does not exists in $my_str, and the to split the result by this single char.
And one char which probable does not exists in $my_str is something like "\x00".

So, a line like
set list_str [split [string map [list "\n\n" "\x00"] $my_str] "\x00"]
is exactly what you need