O'Reilly logo

Learning AWK Programming by Shiwang Kalkhanda

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Controlling variable scope

All variables in AWK are global, except when we make variables local to function. To make a variable local to a function, we simply declare the variable as an argument after the other function arguments.

The following example explains the scope of a variable. Here, q is a global variable declared in the BEGIN block and p is local variable of the one() function, where and is passed to the function as a parameter list:

$ vi func2.awkfunction one(p){    result = p + q    print "p + q : ", result    print "local variable \"p\" : ", p    print "global variable \"q\" : ", q}BEGIN    {    q = 10    one(5)    print "value of p : ", p    print "value of q : ", q}$ awk -f func2.awk

The output of the execution of the previous code is as follows:

p + ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required