compare array between shell and tcl

shell array :

shell use [] as array index. use  ${a[1]} to get value

$ a[1]=1
$ echo  ${a[1]}

1

error :

$ echo "$a[1]"
[1]

注意下面的方法在shell中是不可以的

$ cat  1.sh
#!/bin/ksh
i=1
a[1]="a"
echo "$a[$i]"

 

但是tcl数组是可以的

$ cat 2.exp
#!/opt/exp/bin/expect
set i "1"
set a(1) "a"
puts "$a($i)

 

set -A colorTable $cRed $cGreen $cYellow $cBlue $cFuchsia $cCyan $cWhite

----

tcl use () as array index. use $C(1) to get value

set C(1) 1

set a "$C(1)" 

 

In ksh, arrays are simple arrays that indexed by a number.  There is a limit to the size of the ksh array.  Most systems support indices 0-4095.  After that you will get a “subscript out of range” error.

In tcl, arrays are associative arrays.  The index is a text string.  (You can use numbers 0, 1, 2, etc., but tcl will just interpret it as text.)  Associative arrays are much more powerful because you can map from one string to another, which is a very useful capability.  (The entire C array in xcoolit utilizes this heavily.)

You can set up an entire array in ksh via ‘set –A <arrayName> <values…>’.  For example:
    set –A myArray a b c d e
will set myArray[0]=a myArray[1]=b …

tcl also has a similar capability via ‘array set <arrayName> { <key1> <value1> <key2> <value2> … }’
but we doesn’t utilize this capability anywhere in our tools.

For both ksh and tcl, you can set individual array items as you have already seen:
Ksh: myArray[<nx>]=<value>
Tcl:  set myArray(<nx>) <value>

Similarly, you can unset array items for individual array elements or for the entire array:
Ksh: unset myArray[<nx>]
Ksh: unset myArray
Tcl: unset myArray(<nx>)
Tcl: unset myArray

In ksh, you can dump all array contents by using index ‘*’ (ex. ${myArray[*]}).  You can dump the number of elements in the array via the ‘#’ (length) specifier along with index ‘*’ (ex. ${#myArray[*]}).

In tcl, you can dump all keys of an array via ‘array names’ (ex. foreach nx [array names myArray] { … } ).  The ‘array names’ command also accepts an optional parameter to limit the returned keys to only those that match the pattern (ex. ‘array names myArray abc*’ to only match keys that start with abc).

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值