Local variable in functions (gawk)

Hi Everybody :slight_smile:

I need your help, because i know a local variable in a function for example k, it is different of other variable(with the same name k) this a global variable. Is that right?

dgawk> run
Starting program: 
3238860128818202
3 4 7 11 12 13 17 22 23 32 35 37 41 48 49 55 63 
Stopping in Rule ...
Breakpoint 1, main() at `deco-int.awk':16
16          parseo_datos();
dgawk> s
parseo_datos() at `deco-int.awk':88
88       k = 1;
dgawk> s
89       inicio = 69;
dgawk> s
90       while (k <= 15) {
dgawk> set k=10
k = 10
dgawk> set inicio=177
inicio = 177
dgawk> p k
k = 10
dgawk> p inicio
inicio = 177
dgawk> s
91            i = campo_enc[k];
dgawk> s
92            data=0;
dgawk> p i
i = "32"
dgawk> s
93            long_data=0;
dgawk> s
94            if (C[i,4] == "F") {
dgawk> s
99            if (C[i,4] == "V") {
dgawk> s
100              long_data = strtonum(quita_ceros(cadhex_to_caddec(substr($0, inicio, C[i,5] * 2))));
dgawk> p C[32,4]
C["324"] = "V"
dgawk> p k
k = 10
dgawk> s
100              long_data = strtonum(quita_ceros(cadhex_to_caddec(substr($0, inicio, C[i,5] * 2))));
dgawk> p k
k = 10
dgawk> n
101              if (long_data <= C[i,6]) {
dgawk> p k
k = 1

the function "quita_ceros", I have it in include file:

function quita_ceros(cad)
{
 k=1;
 while (k <= length(cad)) {
      if (substr(cad , k , 1) == "0") {
         cad = substr(cad, k + 1, length(cad));
         continue;
        }
      else
          break;
      k++;
     }
 return cad;
}

if you see the debug, the value of variable global change after call the function "quita_ceros", why? both variable have the same name, but a is local variable and other is a variable global.

Thanks for advance.:b:

Please use the 'CODE' tags for code blocks - please edit.
Use icode tags for short parts only.

Thank you

If you just specify a variable inside an awk function, it becomes a global variable.

In awk you can make the variable "k" local to the function by putting it in the function header. The convention (for readability of your code) is to use a TAB character or extra spaces between the parameters and the local variables. You then call the function using only the parameter before the TAB, like so:

function quita_ceros(cad,      k)

You then call the function like this:

quita_ceros(var1)

then the cad variable is local, call by value and the k variable is not called and is just local to the function..

hi Sea:

Ok, I'm sorry, I am waiting someone i can help with this topic, please.

Thank you.

Hi solaris21,
Did you see Scrutinizer's response in post #3 in this thread?

Did you try what he suggested? Doesn't changing:

function quita_ceros(cad)

in your function definition to:

function quita_ceros(cad,      k)

work for you?

Hi Scrutinizer/Don Cragun:

you're right!!, I put the function as you said me

function quita_ceros(cad, k)

Thanks to all, Regards from Mexico