Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from a list in Tcl?

Tags:

list

tcl

I have a list in Tcl as:

set list1 {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9}

then how could I get the element based on the index of list? for example:

I want to get the second element of this list? or the sixth one of this list?

like image 867
user2131316 Avatar asked Oct 02 '13 12:10

user2131316


People also ask

How do you find the index of an element in a list in Tcl?

To see if an element exists within a list, use the lsearch function: if {[lsearch -exact $myList 4] >= 0} { puts "Found 4 in myList!" } The lsearch function returns the index of the first found element or -1 if the given element wasn't found.

What does lindex mean in Tcl?

DESCRIPTION. The lindex command accepts a parameter, list, which it treats as a Tcl list. It also accepts zero or more indices into the list. The indices may be presented either consecutively on the command line, or grouped in a Tcl list and presented as a single argument.

How do I use Lappend in Tcl?

Lappend is similar to append except that the values are appended as list elements rather than raw text. This command provides a relatively efficient way to build up large lists. For example, ``lappend a $b'' is much more efficient than ``set a [concat $a [list $b]]'' when $a is long.

What is Lrange in Tcl?

The lrange Command The third argument is the index of the last element of the range (so to select one element, the second index should be the same as the first). If the second index is the string end , the range extends to the end of the list.


1 Answers

Just use split and loop?

foreach n [split $list1 ","] {
    puts [string trim $n]  ;# Trim to remove the extra space after the comma
}

[split $list1 ","] returns a list containing 0x1 { 0x2} { 0x3} { 0x4} { 0x5} { 0x6} { 0x7} { 0x8} { 0x9}

The foreach loop iterates over each element of the list and assign the current element to $n.

[string trim $n] then removes trailing spaces (if any) and puts prints the result.


EDIT:

To get the nth element of the list, use the lindex function:

% puts [lindex $list1 1]
0x2
% puts [lindex $list1 5]
0x6

The index is 0-based, so you have to remove 1 from the index you need to pull from the list.

like image 155
Jerry Avatar answered Oct 02 '22 17:10

Jerry