Pac
Pac

Reputation: 23

storage in tcl,using generated values for the same program?

I have a tcl code which generates some values for some arguments.now i want to store these values and use them with the same program but different arguments.how can it be done ?

Upvotes: 0

Views: 39

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137577

To store a value for later in one run of the overall program, put it in a variable.

set theVariable "the value is foo bar"

To store a value for later in another run of the program, you probably need to write it to a file. The simplest way is like this:

# To store:
set f [open theSettingsFile.dat w]
puts $f $theVariable
close $f
# To load:
set f [open theSettingsFile.dat]
set theVariable [gets $f]
close $f

Tcl being Tcl, you could also store it as a script that you can source:

# To store:
set f [open theSettingsFile.tcl]
puts $f [list set theVariable $theVariable]
close $f
# To load:
source theSettingsFile.tcl

For complex things, using a database like SQLite might be a good idea:

# To store:
package require sqlite3
sqlite3 db theSettings.db
db eval {CREATE TABLE IF NOT EXISTS settings (key TEXT, value TEXT)}
# Note; the below is SQL-injection safe    
db eval {INSERT INTO settings (key, value) VALUES ('theVariable',$theVariable)}
db close
# To load:
package require sqlite3
sqlite3 db theSettings.db
db eval {SELECT value FROM settings WHERE key = 'theVariable'} {
    set theVariable $value
}
db close

But that's massive overkill for saving a single simple string.

Upvotes: 1

Related Questions