如何在tcl中循环变量 [英] How to loop a variable in tcl

查看:575
本文介绍了如何在tcl中循环变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是tcl的新手.我对能否在tcl中循环变量存有疑问.

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

我设置了称为handle的变量,即

I have set variable called handle i.e

set handle [pcap open -ip 192.168.1.3] 

这将创建一个句柄pcap0.我想知道是否可以在tcl中循环此变量,以便一次可以创建十个句柄.

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.

在Tcl中,列表是一个,其中包含其他(任意)值的序列.您可以使用lappend将变量添加到列表的末尾,并使用foreach遍历列表.

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.使用数组

在Tcl中,数组是由关联映射支持的复合变量(您可以通过所需的任何值(不一定是数字)来查找事物.他们可以很好地处理列表.

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.

这篇关于如何在tcl中循环变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆