简体   繁体   中英

How to loop a variable in tcl

I am new to tcl. I have some doubt regarding can i loop a variable in tcl.

I have set variable called handle ie

set handle [pcap open -ip 192.168.1.3] 

This creates a handle pcap0. I wanna know whether can i loop this variable in tcl so that at a time i can create a ten handles.

You have two options: lists and arrays.

1. Using a list

In Tcl, a list is a value that contains a sequence of other (arbitrary) values. You can add things to the end of a list in a variable with lappend , and iterate over the list with foreach .

foreach ipaddress {192.168.1.3 192.168.1.4 192.168.1.5 ...} {
    lappend handles [pcap open -ip $ipaddress]
}

foreach handle $handles {
    # Do something with $handle here
}

2. Using an array

In Tcl, an array is a composite variable backed by an associative map (you look things up by any value you want, not necessarily a number). They can work quite well with lists.

set the_addresses {192.168.1.3 192.168.1.4 192.168.1.5 ...}
foreach ipaddress $the_addresses {
    set handle($ipaddress) [pcap open -ip $ipaddress]
}

foreach ipaddress $the_addresses {
    # Do something with $handle($ipaddress) here
}

Which option is best depends on the details of what you are doing.

Donal gave what seemed to be the complete answer, if the IP address is the same, simply do:

set handles ""
set ipaddress 192.168.1.3
for {set i 0} {$i < 10} {incr i} {
    lappend handles [pcap open -ip $ipaddress]
}

foreach handle $handles {
    # Do something with $handle here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM