Storing raw Tcl values

In some cases, you may decide not to use any additional packages, yet you will need to save some data for future usage. In Tcl, it is easy to store data structures like lists or dictionaries in flat text file.

First, let's demonstrate how to write to and read from a list:

set book1 [list {Learning Nagios 3.0} 978-1-847195-18-0]
set book2 [list {Tcl Network Programming} 978-1-849510-96-7]
set books [list $book1 $book2]
puts [lindex [lindex $books end] 0]
set channel [open data.txt w]
puts $channel $books
close $channel
set channel [open data.txt r]
set books [read $channel]
close $channel
puts [lindex [lindex $books end] 0]

books variable is a list of two lists, each one containing the title and ISBN number, respectively. Before saving, we print out the name of the second book. Then, the $books is written to data.txt file, and in the next lines its contents are read and stored again into the books variable. It is the unique Tcl feature that allows treating lists as normal text strings and vice versa, therefore after reading the file we are able to access the variable in a list-like way and print the same title again, for verification:

Tcl Network Programming
Tcl Network Programming

Next, let's do the same thing, but with a dictionary object:

dict set books book1 title {Learning Nagios 3.0}
dict set books book1 isbn 978-1-847195-18-0
dict set books book2 title {Tcl Network Programming}
dict set books book2 isbn 978-1-849510-96-7
puts [dict get $books book2 title]
set channel [open data2.txt w]
puts $channel $books
close $channel
set channel [open data2.txt r]
set books [read $channel]
close $channel
puts [dict get $books book2 title]

Thanks to Tcl's way of internally treating of structures like lists or dictionaries, no additional conversion or serialization is required. As you can see, the procedure is identical, basically puts and read commands handle all the storage issues. In this case, the output is identical as in previous example:

Tcl Network Programming
Tcl Network Programming

Tip

Limitations

Note that such a way of storing and retrieving data works only with text information. If you have some other kind of data in your list, for example handles to objects, its meaning would be lost.

Encoding

We did not mention encoding in this section, it will not be necessary if you are using only one platform. If you are aiming for cross platform portability, we recommend the following configuration of the channel:

fconfigure $channel -translation lf -encoding binary

Another option is to set encoding to utf-8, which will preserve all Unicode data as well as binary data. For example:

fconfigure $channel -translation lf -encoding utf-8

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.105.159