2
votes

I generate a few variables in my tcl script which are actually used as switches for a perl script.

my switches are -X, -Y and -Z, I store them in a variable, cmd with set cmd "-X -Y -Z"

I use exec to run the perl script in tcl like this:

exec ./script.pl $cmd

which throws an error: "Error: Unknown option x -y -z"

then I tried another way:

exec ./script.pl -- $cmd

For this particular case, the perl script gets executed but without the switches i.e. switches don't get activated.

Is there any way to resolve this?

1
I suspect your shell is parsing -X -Y -Z as one flag, you need to split them into three separate arguments.ŹV -

1 Answers

3
votes
set cmd "-X -Y -Z"

Creates a single string with -X -Y -Z in it. When you call the exec command with exec ./script.pl $cmd, you are passing a single argument with -X -Y -Z. What you want are three separate arguments. The best way to do this is:

 exec ./script.pl {*}$cmd

The {*} operator expands a list into its component words.

This is very useful. You can build up your argument list with code similar to (an example):

set cmd {}
lappend cmd -X
if { $mytest eq "true" } {
   lappend cmd -Y 
}
lappend cmd -Z
if { $filename ne {} } {
  lappend cmd -f
  lappend cmd $filename
}
exec ./script.pl {*}$cmd

With older versions of Tcl, the eval command must be used:

eval exec ./script.pl $cmd

Edit: -- argument to exec

The -- argument to exec specifies that no more switches (options) will be parsed by exec. This allows exec to be used for the cases when a command starts with a -. e.g.

 exec -- -myweirdcommand

References: Tcl Syntax (#5); eval; exec