Obtaining array values in Tcl - arrays

I have tcl arrays having the names as 0,1,2,.. and the values contain meaningful information.
I want to use a single command like [array names $my_array] to get the values of the array.
Right now I only see this option,(lengthy but gets job done)
for {set index 0} {$index<[array size my_array]} {incr index} {
lappend my_list_values $my_array($index)
}

You can use array get to fetch all the elements of the array, and a foreach loop that consumes multiple elements of its list in each iteration (Plus sorting by key to get a reproducible order):
% set foo(0) a
a
% set foo(1) b
b
% set foo(2) c
c
% foreach {key val} [lsort -integer -stride 2 [array get foo]] { lappend values $val }
% puts $values
a b c
%
Or with array names:
foreach key [lsort -integer [array names foo]] { lappend values $foo($key) }

Here's a proc implementing a foreach functionality for arrays. In Tcl 8.7 this will be builtin: array for
# A note on performance: we're not saving any time with this approach.
# This is essentially `foreach name [array names ary] {...}
# We are saving memory: iterating over the names versus extracting
# them all at the beginning.
#
proc array_foreach {vars arrayName body} {
if {[llength $vars] != 2} {
error {array foreach: "vars" must be a 2 element list}
}
lassign $vars keyVar valueVar
# Using the complicated `upvar 1 $arrayName $arrayName` so that any
# error messages propagate up with the user's array name
upvar 1 $arrayName $arrayName \
$keyVar key \
$valueVar value
set sid [array startsearch $arrayName]
# If the array is modified while a search is ongoing, the searchID will
# be invalidated: wrap the commands that use $sid in a try block.
try {
while {[array anymore $arrayName $sid]} {
set key [array nextelement $arrayName $sid]
set value [set "${arrayName}($key)"]
uplevel 1 $body
}
} trap {TCL LOOKUP ARRAYSEARCH} {"" e} {
puts stderr [list $e]
dict set e -errorinfo "detected attempt to add/delete array keys while iterating"
return -options $e
} finally {
array donesearch $arrayName $sid
}
return
}
You can add this to the array ensemble:
set map [namespace ensemble configure array -map]
dict set map foreach ::array_foreach
namespace ensemble configure array -map $map
then
% array set a {foo bar baz qux}
% array foreach {key value} a {puts "key=$key, value=$value"}
key=foo, value=bar
key=baz, value=qux

Related

How would I sort file using Tcl according to size of those files?

I have a list of files and a separate list of sizes of those files using "file size <file_name>".
I am required to sort the files in ascending order based on the size and then feed it further for processing.
Can someone provide a step by step process I could follow?
This is what I have done so far
set direc "<Any direcotry to look files at>"
set folderFiles [glob -directory $direc -nocomplain -type f *.xml]
set fileSizes []
puts "Files to be processed are:"
puts "$folderFiles"
puts "Sizes of files in this order are:"
foreach tempFile $folderFiles {
lappend fileSizes [file size $tempFile]
}
puts $fileSizes
set fileDict [dict create [lindex $folderFiles 0] [lindex $fileSizes 0]]
for {set i 1} {$i < [llength $folderFiles]} {incr i} {
dict lappend fileDict [lindex $folderFiles $i] [lindex $fileSizes $i]
}
puts $fileDict
So, this gives me a dictionary where keys -> files and values -> file sizes. I just need to sort this dictionary based on values which are file sizes.
The first thing you need to do is to get the list of filenames and their sizes. You can keep the sizes separately.
set filenames [glob -type f *.foo]; # Or whatever
set sizes [lmap f $filenames {file size $f}]
Then we sort the sizes, but get the indices of the sort back rather than the sorted list.
set indices [lsort -indices -integer $sizes]
Now, we use those indices to construct the sorted filenames:
set filenames [lmap idx $indices {lindex $filenames $idx}]
We can combine some of these things into a helper procedure:
proc SortFilesBySize {filenames} {
set sizes [lmap f $filenames {file size $f}]
return [lmap idx [lsort -indices -integer $sizes] {lindex $filenames $idx}]
}
set filenames [glob -type f *.foo]; # Or whatever
puts [join [SortFilesBySize $filenames] "\n"]
One way:
#!/usr/bin/env tclsh
proc zip {list1 list2} {
lmap a $list1 b $list2 { list $a $b }
}
proc heads {pairs} {
lmap pair $pairs { lindex $pair 0 }
}
proc sort_by_size {names sizes} {
heads [lsort -integer -increasing -index 1 [zip $names $sizes]]
}
set names {a.txt b.txt c.txt}
set sizes {3 2 1}
puts [sort_by_size $names $sizes]
Combines the names and sizes into a list of pairs of filename and size, sorts based on size, and then returns just the reordered filenames. Essentially a tcl version of perl's classic Schwartzian Transform idiom.

How to print multiple arrays in TCL?

#!/usr/bin/expect -f
set myarr1(chicken) animal
set myarr1(cows) animal
set myarr1(tiger) animal
set myarr1(horse) animal
set myarr2(carrot) vegetable
set myarr2(tomato) vegetable
set myarr2(potato) vegetable
set myarr2(pea) vegetable
set arr_list { myarr1 myarr2 }
foreach key [array names [lindex $arr_list 0]] {
puts "${key}=$[lindex $arr_list 0]($key)"
}
foreach key [array names [lindex $arr_list 1]] {
puts "${key}=$[lindex $arr_list 1]($key)"
}
Output obtained:
cows=$myarr1(cows)
horse=$myarr1(horse)
chicken=$myarr1(chicken)
tiger=$myarr1(tiger)
tomato=$myarr2(tomato)
pea=$myarr2(pea)
potato=$myarr2(potato)
carrot=$myarr2(carrot)
Required output:
cows=animal
horse=animal
chicken=animal
tiger=animal
tomato=vegetable
pea=vegetable
potato=vegetable
carrot=vegetable
I am able to get the required output if I use the following in foreach loop:
foreach key [array names myarr1] {
puts "${key}=$myarr1($key)"
}
foreach key [array names myarr2] {
puts "${key}=$myarr2($key)"
}
I am trying to create a list of array names and then loop through that list of array names and print it. If there is a better way to approach this problem, I am all ears. Thanks for the assist !
You really ought to use nested foreachs for that.
foreach arr $arr_list {
foreach key [array names $arr] {
puts "${key}=$$arr($key)"
}
}
Except that doesn't work! Why? It's easy on one level: the syntax for $ doesn't support such complexity; it really only supports a (very useful) subset of legal variable names and can't do complicated substitutions (array element names support more diverse options). We need to rewrite to use the single-argument set form as a first step:
foreach arr $arr_list {
foreach key [array names $arr] {
puts "${key}=[set [set arr]($key)]"
}
}
That works, but isn't very elegant (or fast, for that matter). It's actually better to use upvar 0 to make a local alias to the array that you're processing; variable alias from a to whatever was talked about with $arr will let us shorten things elsewhere, and it's pretty elegant in practice:
foreach arr $arr_list {
upvar 0 $arr a
foreach key [array names a] {
puts "$key=$a($key)"
}
}
You can also do things like sorting the list of element names (array names does not guarantee to return things in any particular order), putting spacing in between each of the arrays that you print out, etc. But that's the core of how to improve things. You can also use array get instead of array names and a multi-variable foreach, but then sorting the keys is more awkward (well, before Tcl 8.6's lsort gained the -stride option).
If you just want to print them, use the bundled parray proc:
foreach arr $arr_list {
parray $arr
}
which outputs
myarr1(chicken) = animal
myarr1(cows) = animal
myarr1(horse) = animal
myarr1(tiger) = animal
myarr2(carrot) = vegetable
myarr2(pea) = vegetable
myarr2(potato) = vegetable
myarr2(tomato) = vegetable
You can use the foreach command to traverse both the keys and the values in the array.
array set arr {a 1 b 2 c 3}
foreach {k v} [array get arr] {
puts $k=$v
}
References: foreach
You're on the right track with the foreach command, but to loop over the list of arrays you need to nest it:
foreach arr $arr_list {
foreach {key val} [array get arr] {
puts "$key = $val"
}
}
Also, look into the parray command, and see if that style of printing works for what you need. (I'd link it, but the site appears to be down at the moment. I'll try to remember to edit this later. Check out the command details at http://www.tcl.tk/man/tcl8.6/)
What you probably want is:
foreach arr $arr_list {
foreach key [array names $arr] {
puts "$key=[set ${arr}($key)]"
}
}
That said, you’re using arrays in a non-standard way that possibly is suboptimal. Have you looked into dictionaries? (Unfortunately, discussing how your data should be structured isn’t a Stackoverflow topic.)

List of Array tcl

I have 5 arrays and i want to iterate over them one by one, so I'm thinking to add these arrays to another array and access them one by one with indexes
array set ListOfArrays {1 $array1 2 $array2 3 $array3 4 $array4 5 $array5}
for { set i 1} { $i <= 5 } {incr i} {
set list $ListOfArrays($i)
foreach {key} [array names list] {
puts $key
}
}
The output is empty...
what is wrong?!
Tcl's arrays can't be put in a list; they're (collections of) variables, not values. But you can put the names of the arrays in.
array set ListOfArrays {1 array1 2 array2 3 array3 4 array4 5 array5}
for { set i 1} { $i <= 5 } {incr i} {
upvar 0 $ListOfArrays($i) list
foreach {key} [array names list] {
puts $key
}
}
The upvar 0? It makes a local alias to a variable, and it's great for this sort of thing.
As an alternative to the array-based solutions, a solution using dictionaries. I borrow the data from Jerry's answer.
set dict1 {1 a 2 b}
set dict2 {3 c 4 d}
set dict3 {5 e 6 f}
set dict4 {7 g 8 h}
set dict5 {9 i 10 j}
set dicts [list $dict1 $dict2 $dict3 $dict4 $dict5]
foreach dict $dicts {
foreach key [dict keys $dict] {
puts $key
}
}
Unlike arrays, dictionaries can be passed as values and evaluated using $. This means that you can put your five dictionaries in a list and traverse that list with foreach. In the inner loop, each key is printed.
foreach dict $dicts {
dict for {key -} $dict {
puts $key
}
}
is basically the same thing.
Documentation: dict, foreach, list, puts, set

Changing item in list by index in TCL

Im trying to work with this awful language and I have to change an item of list by accessing to it with index
set FileRead [open "$flPath" r]
set Data [read $FileRead]
set DataList [split $Data "\n"] #Guess that it creates a list, not an array right?
for {set i 1} { $i < [llength $DataList]} {incr i} {
set line [lindex $DataList $i]
#Some changes on $line
lreplace $DataList $i $line # Thought this should replace the DataList[$i] with my $line
}
I dont understand the awful syntax of TCL! How can I realise it?
You shouldn't just call a language awful because you don't know how to use it, otherwise, just don't use it at all...
In any case, you should read the documentation of lreplace. You supply:
lreplace list first last ?element element ...?
To replace the line in the list of DataList, you thus should change your line to:
lreplace $DataList $i $i $line
This will replace the ith item in DataList with the string in line.
However, this will not change the list DataList at all you need to set the result of the lreplace to a variable (lreplace does not alter the list DataList directly) like...
set DataList [lreplace $DataList $i $i $line]
Though if you are changing only one item in the list at a time, it would be better to use lset:
set FileRead [open "$flPath" r]
set Data [read $FileRead]
set DataList [split $Data "\n"] #Guess that it creates a list, not an array right?
for {set i 1} { $i < [llength $DataList]} {incr i} {
set line [lindex $DataList $i]
# Some changes on $line
lset DataList $i $line
}
lset unlike lreplace does not need to be set since it changes the list in addition to returning the substituted list.
If you are changing every item in a list, and the new value can be produced by a simple script, lmap (list map) is the way to go. The command creates a list with the same number of items as the original list, where each item in the new list has the value of the script with the value of the corresponding item in the original list inserted. Say you want to count characters for each item in a list:
set list [list can be produced]
lmap item $list {
list $item [string length $item]
}
# => {{can 3} {be 2} {produced 8}}
Note that this command does not change the value of list: you need to assign it back to update the value.
The linsert (list insert) adds new items to a list without removing any of the existing elements:
set list [list can be produced]
linsert $list 1 not
# => {can not be produced}
The lreplace (list replace) is mostly useful for insertions that change the number of elements in a list:
set list [list can be produced]
lreplace $list 0 1 can sometimes but not always be
# => {can sometimes but not always be produced}
set list [list the new value can be produced]
lreplace $list 1 1
# => {the value can be produced}
Again, the value of list isn't changed by linsert or lreplace.
If you want to change an item in a list in place, lset (list set) is your friend:
set list [list the new value can be produced]
lset list 1 correct
# => {the correct value can be produced}
This command does change the value of list, because it belongs to the family of setting commands that take a variable name rather than a variable value, and modify the value in some way.
Documentation: linsert, list, lmap, lreplace, lset, set, string

After using array get, how to remove the indexes in TCL

I have a proc which finishes off with an array. To return it I use "array get" to retrive a list. This list however does not only contain my array entrys, but also their index:
So my array [ a b c d ] turns into a list { 0 a 1 b 2 c 3 d }
How can i get rid of these index numbers without disturbing the list order?
A few options, apart from using foreach:
# [array get] actually returns a dictionary
puts [dict values $list]
# Could do this too
set entrylist {}
dict for {- entry} $list {
lappend entrylist $entry
}
puts $entrylist
There are more possibilities in Tcl 8.6:
puts [lmap {- entry} $list {set entry}]
(There's also a dict map, but it isn't useful here.)
I like dict values…
The simplest and most basic way I think would be to use a foreach loop:
% set list {0 a 1 b 2 c 3 d}
% set entrylist {}
% foreach {id entry} $list {
% lappend entrylist $entry
% }
% puts $entrylist
a b c d
If you already have an array and work with Tcl 8.5 or later, use dict values:
set arr(0) a
set arr(1) b
set arr(2) c
set arr(3) d
puts [dict values [array get arr]]
But it is better to use a simple list:
set mylist {a b c d}
lset list 1 boo
puts [lindex $mylist 1]
lappend mylist eff
Arrays are associative. Always.

Resources