2

Can someone explain why this keeps failing?

set hostname ""

if {$hostname eq ""} {
   puts "Usage: host [-u username] [-p password] [-f]"
   exit 5
}

if {[string length $hostname] == 0} {
   puts "Usage: host [-u username] [-p password] [-f]"
   exit 5
}

 if {[string equal $hostname ""]} {
   puts "Usage: host [-u username] [-p password] [-f]"
   exit 5
}

I get the following error:

invalid command name "-u"
    while executing
"-u username"
    invoked from within
"if {$s eq ""} {puts "Usage: host [-u username] [-p password] [-f]"}"

The code seems to execute fine but I can't seem to use puts with a string that contains braces.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
Zhro
  • 2,546
  • 2
  • 29
  • 39

2 Answers2

8

Square braces inside a double-quoted string means evaluation. Try escaping the square braces with a backslash.

  • 1
    I'm just breaking into Tcl and I've found that it's got quite a few quirks compared to other languages. Thank you for the answer. I've also found that enclosing the string in braces corrects the problem and only additional braces inside the enclosed string need to be escaped. – Zhro Jul 15 '13 at 04:44
  • Yup, Ousterhout got most of it right but the evaluation part has always been Tcl's Achilles Heel. –  Jul 15 '13 at 04:53
  • 8
    @Yatin Actually, the language is _more_ consistent than most others. Brackets always mean the same thing unless you take the trouble to quote them, so you know that you have to take the trouble. Entirely predictable. – Donal Fellows Jul 15 '13 at 05:17
  • @Zhro, consider reading through [the tutorial](http://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html) which explains all these simple things. – kostix Jul 15 '13 at 09:06
  • I don't have matters of religion in languages. I'll use anything. They all have quirks. Tcl was one of the first progressive scripting languages, e.g. allowing one to extend it in C. I enjoyed my time with Tcl and have nothing to say about language comparisons except that they are all good. –  Jul 15 '13 at 20:55
  • It took me a few days of head banging but I'm very comfortable working with Tcl now. Actually, I got so comfortable that I even had some mild frustration moving back over to bash once I finished the script I needed. Yatin is right. Tcl is actually pretty consistent once you understand the basics. – Zhro Jul 23 '13 at 18:02
7

Another approach is to use different quotes for the strings you print:

puts {Usage: host [-u username] [-p password] [-f]}

Braces act like the shell's single quotes: they prevent substitutions within the brace-quoted string.

You might also want to spend some time studying Tcl's 12 syntax rules:
http://www.tcl.tk/man/tcl8.5/TclCmd/Tcl.htm

glenn jackman
  • 238,783
  • 38
  • 220
  • 352