天天看点

awk中变量的作用域

说明awk中变量作用域之前,先看几个测试

测试1:fun1()没有参数,里面的变量x和BEGIN里的x是同一个变量

[email protected]:~$ 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

}

[email protected]:~$ 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变量是两个不同的变量

[email protected]:~$ 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

}

[email protected]:~$ 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中的变量换为数组,参数换为数组名

[email protected]:~$ 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]

}

[email protected]:~$ 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:

[email protected]:~$ cat test4.awk 

BEGIN { 

        fun1()

        fun2()

}

function fun1() {

        x = "Hello"

}

function fun2() {

        print x ? x : "NULL"

}

[email protected]:~$ awk -f test4.awk 

Hello

[email protected]:

测试5:

[email protected]:~$ cat test5.awk 

BEGIN { 

        fun1("Good")

        fun2()

}

function fun1(x) {

        x = "Hello"

}

function fun2() {

        print x ? x : "NULL"

}

[email protected]:~$ awk -f test5.awk 

NULL

通过以上测试,可以看出,变量的作用域是从第一次出现开始,直到整个程序的结束为止。如果变量是在某个函数中出现,那么要看函数定义时的参数中是否有此变量,如果有,那么只在这个函数中有效;否则,从函数被调用开始有效,一直到整个程序结束。如果是数组名作为函数参数,是个例外,因为数组名是个地址。

继续阅读