6

Is it a requirement of good TCL code? What would happen if we don't use the "unset" keyword in a script? Any ill-effects I should know about?

I'm inheriting some legacy code and the errors that come about due to "unset"-ing non-existent variables are driving me up the wall!

chronodekar
  • 2,616
  • 6
  • 31
  • 36

5 Answers5

11

It's possible to determine whether a variable exists before using it, using the info exists command. Be sure that if you're not using unset, that you don't upset the logic of the program somewhere else.

There's no Tcl-specific reason to unset a variable, that is, it's not going to cause a memory leak or run out of variable handles or anything crazy like that. Using unset may be a defensive programming practice, because it prevents future use of a variable after it's no longer relevant. Without knowing more about the exact code you're working with, it's hard to give more detailed info.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • No memory leaks or like. Just what I was hoping to hear! Now I can go banning those idiotic "unset" throughout the code. Yes, looking at it now, seems more of defensive programming to me too. Still, in my case, it looks like a bit "too much" of defense. "info exists" is new to me - thanks! – chronodekar Feb 25 '10 at 06:06
2

In addition to the other responses, if your Tcl version is new enough, you can also use:

unset -nocomplain foo

That'll unset foo if it exists, but won't complain if it doesn't.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
Jeff Godfrey
  • 718
  • 8
  • 18
1

Depends on the system stats it may give "unable to allocate bytes" issue as and when your script is storing huge data into variables and arrays. it'll break once the cache or RAM is full saying "unable to allocate XXXXXXXX bytes".

Make sure you're not storing that much data into variables, otherwise do unset once the use is over for the respective datasets(variables)

0

For note as I don't seem able to comment on the "info exists" above;

I use this form often..

if { [info exists pie] && [$pie == "ThisIsWhatIWantInPie"]} {
    puts "I found what I wanted in pie."
} else {
    puts "Pie did not exist; but I still did not error,TCL's evaluation \
          will see the conditional failed on the [info exists] and not \
          continue onto the comparison."
}
wom
  • 436
  • 5
  • 16
0

In addition to the other responses, I want to add that, if you want to neglect the errors raising as a result of unsetting non-existent variable use 'catch'.

#!/bin/bash

catch {unset newVariable}
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
Ankush Pandit
  • 313
  • 4
  • 18