awk中变量的作用域

35 篇文章 0 订阅
说明awk中变量作用域之前,先看几个测试

测试1:fun1()没有参数,里面的变量x和BEGIN里的x是同一个变量
qingsong@db2a:~$ cat test1.awk 
BEGIN {
        x = "Good"
        fun1()
        print "X in BEGIN is", x
}

function fun1() {
        print "X in fun1 before reassign is", x
        x = "Bad"
        print "X in fun1 after reassign is", x
}
qingsong@db2a:~$ awk -f test1.awk 
X in fun1 before reassign is Good
X in fun1 after reassign is Bad
X in BEGIN is Bad

测试2:fun1()有参数,则里面的变量x仅在函数内部有效,和BEGIN里的x变量是两个不同的变量
qingsong@db2a:~$ cat test2.awk 
BEGIN {
        x = "Good"
        fun1(x)
        print "X in BEGIN is", x
}

function fun1(x) {
        print "X in fun1 before reassign is", x
        x = "Bad"
        print "X in fun1 after reassign is", x
}
qingsong@db2a:~$ awk -f test2.awk
X in fun1 before reassign is Good
X in fun1 after reassign is Bad
X in BEGIN is Good

测试3:把测试2中的变量换为数组,参数换为数组名
qingsong@db2a:~$ cat test3.awk 
BEGIN {
        A[1] = "Good"
        fun1(A)
        print "A[1] in BEGIN is", A[1]
}

function fun1(A) {
        print "A[1] in fun1 before reassign is", A[1]
        A[1] = "Bad"
        print "A[1] in fun1 after reassign is", A[1]
}
qingsong@db2a:~$ awk -f test3.awk 
A[1] in fun1 before reassign is Good
A[1] in fun1 after reassign is Bad
A[1] in BEGIN is Bad

测试4:
qingsong@db2a:~$ cat test4.awk 
BEGIN { 
        fun1()
        fun2()
}

function fun1() {
        x = "Hello"
}

function fun2() {
        print x ? x : "NULL"
}
qingsong@db2a:~$ awk -f test4.awk 
Hello
qingsong@db2a:

测试5:
qingsong@db2a:~$ cat test5.awk 
BEGIN { 
        fun1("Good")
        fun2()
}

function fun1(x) {
        x = "Hello"
}

function fun2() {
        print x ? x : "NULL"
}
qingsong@db2a:~$ awk -f test5.awk 
NULL

通过以上测试,可以看出,变量的作用域是从第一次出现开始,直到整个程序的结束为止。如果变量是在某个函数中出现,那么要看函数定义时的参数中是否有此变量,如果有,那么只在这个函数中有效;否则,从函数被调用开始有效,一直到整个程序结束。如果是数组名作为函数参数,是个例外,因为数组名是个地址。
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值