Monday, December 7, 2015

lists


  • Lists
    • Lists are equivalent to arrays in the conventional programming language like C.
    • Lists can be expanded and collapsed on the fly.

  • Example 1:
    • set list1 "a  b c d"

  • Functions associated with lists :
    • lindex
    • lappend
    • lindex
    • llength
    • lrange
    • lreplace
    • lsearch
    • lsort
    • split
    • join
    • concat
Example 2:
#Initialize a list
set list1 "a b c d"
puts $list1
#Now add words "hello", "world" to above list
lappend list1 hello
puts $list1
lappend list1 world
puts $list1
#When we use lappend to append any string it will be added at the last
#Now list1 has the value "a b c d hello world"
#If we want to refer the string in the 3rd place, Lists index will start from 0 so we need to refer with index=2
puts [lindex $list1 2]; #output will be "c"
#Lets say I want to insert x y z after c, i.e. before the index=2.
#*** IMPORTANT NOTE:
#It will not modify the original list. We need to overwrite the original list by assigning to return value.
set list1 [linsert $list1 2 x y z]
puts $list1
#Lets say I want to replace "c d" with "s t u v". Even lreplace will not modify the original list.
# value of list1 is
#a b x y z c d hello world
set list1 [lreplace $list1 5 6 s t u v] ; #Now the value of list has been updated to "a b x y z s t u v hello world"
puts $list1
#Lets say I want the slice in the list from s to v, it will not modify the original list
puts [lrange $list 5 end-2]
#concat
set list2 "tcl session is very boring"
set mergedlist [concat $list1 $list2]
puts $mergedlist
#llength
puts [llength $mergedlist]
#you might want to replace/trim certain characters in the list
#split
#lets say I am reading a csv file, I want to postprocess the data in the csv file or if I want to print in the readable format.
set list3 "a,b,c,d"
set list4 [split $list3 ,]
#join the words with colon
set list5 [join $list4 :]
#lsearch operations:
set a {Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec}
lsearch -exact $a jun; # output -1
lsearch -exact $a Jun; # output 5
lsearch -glob $a J* ; #output 0
lsearch -glob $a J. ; #output -1
lsearch -glob $a J?? ; #output 0
lsearch -regexp $a {[A-Z]e[a-z]} #output 1, if you don't give curly brace it will issue a syntax error stating invalid command.
view raw lists.tcl hosted with ❤ by GitHub

No comments: