How to get value from a list in Tcl?
Asked Answered
H

3

6

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?

Henebry answered 2/10, 2013 at 12:12 Comment(1)
It's a funny list. All elements except the last one have a comma at the end. Maybe you just want the list elements without the commas. List elements in Tcl are just separated by white space, not commas.Garbage
P
9

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.

Porringer answered 2/10, 2013 at 12:18 Comment(3)
are there any index in the list, can we get the second element? or in this case, should we use array?Henebry
what you mean by a foreach for pairs of values? and one value and one index for array or list?Henebry
@Henebry What are you exactly trying to do? Update your question accordingly please. This is getting confusing :(Porringer
S
8

Just do

lindex $list 2

you will get

0x3
Sienna answered 22/1, 2015 at 11:11 Comment(0)
P
1

You "should" be using lindex for that. But from your question I have te impression that you do not want the "," to be present in the element extracted. You don't need the "," to separate the list. Just the blank space will do.

> set list1 {0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9}
> 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9
> lindex $list1 3
> 0x4
Pinsk answered 6/9, 2019 at 17:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.