文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>《TCL 教程英文版》 笔记 §14 变量作用域-glob..

《TCL 教程英文版》 笔记 §14 变量作用域-glob..

时间:2008-08-26  来源:oychw

§14   变量作用域-global and upvar

       TCL变量的作用域有过程,namespaces,global等。使用global和upvar可以改变作用域。Upvar在当前作用域内把一个变量名和另外一个作用域的变量联系起来。一般用于过程传址。

  • 语法:upvar ?level? otherVar1 myVar1 ?otherVar2 myVar2? ... ?otherVarN myVarN?

实例: 注意蓝色部分,2级引用的时候没有使用$.

 

# cat ch14

# !/bin/bash

# \

exec tclsh "$0" "$@"

 

proc SetPositive {variable value } {

    upvar $variable myvar

    if {$value < 0} {

        set myvar [expr {-$value}]

    } else {

        set myvar $value

    }

    return $myvar

}

 

SetPositive x 5

SetPositive y -5

 

puts "X : $x    Y: $y\n"

 

proc two {y} {

    upvar 1 $y z                    ;# tie the calling value to variable z

    upvar 2 x a                     ;# Tie variable x two levels up  to a

    puts "two: Z: $z A: $a"         ;# Output the values, just to confirm

    set z 1                         ;# Set z, the passed variable to 1;

    set a 2                         ;# Set x, two layers up to 2;

}

 

proc one {y} {

    upvar $y z                      ;# This ties the calling value to variable z

    puts "one: Z: $z"               ;# Output that value, to check it is 5

    two z                           ;# call proc two, which will change the value

}

 

one y                               ;# Call one, and output X and Y after the call.

puts "\nX: $x  Y: $y"

 

 

proc existence {variable} {

    upvar $variable testVar

    if { [info exists testVar] } {

        puts "$variable Exists"

    } else {

        puts "$variable Does Not Exist"

    }

}

 

set x 1

set y 2

for {set i 0} {$i < 5} {incr i} {

    set a($i) $i;

}

 

puts "\ntesting unsetting a simple variable"

# Confirm that x exists.

existence x

# Unset x

puts "x has been unset"

unset x

# Confirm that x no longer exists.

existence x

 

 

执行结果:

# ./ch14

X : 5    Y: 5

 

one: Z: 5

two: Z: 5 A: 5

 

X: 2  Y: 1

 

testing unsetting a simple variable

x Exists

x has been unset

x Does Not Exist

 

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载