user2533429
user2533429

Reputation: 195

How to search for a variable and display the next variable in the list in tcl

Hi I want to search a variable in a list and display the next item in the list. Like If I have a list with " aaa bbb ccc eee fff" I want to search for bbb and display the next one in the list which is in this case ccc. I know we have to use lsearch and find the variable and use lindex to display the next one but I dont know how to move to the next variable.

Upvotes: 2

Views: 839

Answers (2)

Javide
Javide

Reputation: 2637

This is a solution which takes into account the edge cases and returns an empty string if the searched element does not satisfy the conditions:

proc get_item {mylist element option} {

    set i [lsearch $mylist $element]

    if {$i > -1} {
        if {$option == "previous" && $i > 0} {          
            return [lindex $mylist $i-1]
        } elseif {$option == "next" && $i >= 0 && $i < [llength $mylist] - 2} {
            return [lindex $mylist $i+1]
        }
    }

    return ""
}

set a {aaa bbb ccc ddd}
get_item $a bbb next
get_item $a bbb previous 

Upvotes: 1

nurdglaw
nurdglaw

Reputation: 2117

Is this what you're after?

set l {aaa bbb ccc eee fff}

set index [lsearch $l bbb]
incr index
set required [lindex $l $index]

It puts ccc into the variable required.

Upvotes: 3

Related Questions