Variable scoping in AWK
A variable is defined as storage location to store some value in it so that we can use this in a program. Variables will protect us from varying values in the storage location. This will help us to avoid hardcoding values in a program where ever it’s used. We can define a variable at the start of program and use the variable across the program, if we want to change the value of it, we can change it where we define it and this value will be updated where ever we use that variable.
Awk is an interpreted programming language, similar to JavaScript and Python in that there is need to compile into machine language. Awk is used for text processing and editing, manipulating data easily. Unlike Python, there is no way to make a variable local to a block in awk. Like Bash and JavaScript, any function declared outside the function belongs to the global scope.
function myFunc1() { for (idx = 0; idx < 5; idx++) print "myFunc's idx = " i } BEGIN { idx = 10 myFunc1() print "idx in the global = " idx }
The output will be the following :
myFunc's idx = 0 myFunc's idx = 1 myFunc's idx = 2 myFunc's idx = 3 myFunc's idx = 4 idx in the global = 5
Function scoping
It is good practice to do so whenever a variable is needed only in that function. Declaring a variable in a function scope is different from Bash and JavaScript. does variable local to a function. In JavaScript, to declare a variable in the function, you simply declare the variable. In Bash, you will have to declare the variable inside the function with the keyword "local". In AWK, to make a variable local to a function, simply declare the variable as an argument after the actual function arguments. It is a coding convention to add spaces to before the variable to show that it is a local variable.
function myFunc(p_param, l_local_var) { l_local_var = p_param + 1 print "myFunc = " l_local_var } BEGIN { idx = 10 myFunc(idx) }
Block scoping
Unlike Python, there is no way to make a variable local to a block in awk. Like Bash and JavaScript, any function declared outside the function belongs to the global scope.