Tcl之过程与作用域

1、proc:过程定义命令

语法:proc proName {var1 var2...} {

        body

}

当proc带有默认参数时,第一种情况默认参数在后面,那么只需要输入非默认参数的值,第二种情况,默认参数之后还有非默认参数输入,那么在调用的时候 需要加上默认参数(当然默认参数的数值可以改变)

proc Test {a {b 7} {str "hello world"} } {
    puts "$str"
    return [expr $a * $b]
}
Test 10
Test 10 5 "call test"

proc Test2 {{a 7} b } {
    puts [expr $a * $b]
}
Test2 5 7
Test2 7 7

不定输入参数时 

%proc vParam {args} { ;  #定义一个只接收可变数目参数的过程。 
 puts "input values are : $args" 
} 
% vParam ;#没有给定任何参数值时 
=> input values are : 
% vParam 1 "Hello" 2 3 "End" ;#给定一组任意值 
=> input values are : 1 Hello 2 3 End 

参数名+参数值成对输入的过程定义

proc config {args} {
    array set inarr $args #将一个列表转换成一个数组
    parray inarr          #打印出inarr所有的元素和变量名
}
config sysName "HUB100" ipAddr 192.168.1.1 date 2023-11-11 time 21:03



inarr(date)    = 2023-11-11
inarr(ipAddr)  = 192.168.1.1
inarr(sysName) = HUB100
inarr(time)    = 21:03

2、过程的作用域

一般情况下,过程的作用域即全局作用域,所以可以再脚本的任何一个过程使用过程。

但是过程时可以嵌套的,低层次的过程只有在上层过程被执行后才能生效。

proc one {} {
    puts "i'm one"
    proc two {} {
        puts "i'm two"
    }
    puts "call two in one"
    two 
}

one

i'm one
call two in one
i'm two


two
i'm two

3、变量的作用域

局部变量:过程体内定义的变量,只在过程体中有效。

全局变量:在所有过程体之外定义的变量,作用域为从开始定义到执行结束。

全局变量可以再过程内部使用,但是需要用global提前说明。

set a 5 
set b –8 
set c 10 
proc P1 {a} { 
set b 42 
global c 
puts "Value of Input parameter a is $a" 
puts "My b is $b" 
puts "Global c is $c" 

} 
%P1 $b 
=> Value of Input parameter a is -8 
 My b is 42 
Global c is 10 

4、upvar命令

与global的作用相似,upvar通过“引用”来使用上层过程中的变量。在某些特定参数(情况)下,等于global,但是区别是upvar可以调用别的层的参数。

5、rename命令

用来更改命令名。

语法:rename oldfunname newfunname;其中如果newfunname为空字符串{},则此时rename为取消一个命令。

proc old {} {
puts "This is a fun"

}
old
rename old new

new

6、命令行参数

;# STEP1: Create script: 
;#please save follow script into cmdline.tcl 
;# sample s cript : cmdline.tcl 
puts "The number of command line arguments is: $argc" 
puts "The name of the scriptis: $argv0" 
puts "The command line arguments are: $argv" 

 

;#STEP2: Call tclsh to run cmdline.tcl: 
E:\> tclsh cmdline.tcl 
=> The number of command line arguments is: 0 
The name of the scriptis: cmdline.tcl 
The command line arguments are: 
E:\>tclsh cmdline.tcl a b c d e 
=> The number of command line arguments is: 5 
The name of the scriptis: cmdline.tcl 
The command line arguments are: a b c d e 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值