No awk, quando é executada uma definição de função?

0

No awk, quando é executada uma definição de função?

Uma definição de função é executada mesmo antes de o BEGIN {...} ser executado? Obrigado.

    
por Tim 15.11.2018 / 01:57

1 resposta

3

Isso é facilmente determinado; Fiquei curioso e decidi testar primeiro o cenário "pior cenário", definindo a função no final do arquivo de script awk:

$ cat go.awk
BEGIN {
  print "The BEGIN block is executing"
  print reverse("The BEGIN block is executing")
}

{
  print reverse($0)
}

function reverse(str) {
  trs=""
  for(i=length(str); i > 0; i--) {
    trs=trs substr(str, i, 1);
  }
  return trs
}

E com:

$ cat input
line one
line two
line three

... o resultado é:

$ awk -f go.awk < input
The BEGIN block is executing
gnitucexe si kcolb NIGEB ehT
eno enil
owt enil
eerht enil

Você pode ver que a função foi definida (a função "definição" foi "executada") antes que o bloco BEGIN fosse inserido, já que o bloco BEGIN chamou minha função reverse definida pelo usuário.

Para ver que a função não é executada enquanto está sendo definida, basta inserir uma instrução print dentro da função e observar que não há saída dessa instrução até que a função seja chamado .

A especificação POSIX para o awk diz, mais pertinente:

A function can be referred to anywhere in an awk program; in particular, its use can precede its definition. The scope of a function is global.

A página de manual do gawk sugere algo semelhante:

... Gawk reads the program text as if all the program-files and command line source texts had been concatenated together. This is useful for building libraries of AWK functions, without having to include them in each new AWK program that uses them. It also provides the ability to mix library functions with command line programs.

...

Gawk executes AWK programs in the following order. First, all variable assignments specified via the -v option are performed. Next, gawk compiles the program into an internal form. Then, gawk executes the code in the BEGIN rule(s) (if any), and then proceeds ...

    
por 15.11.2018 / 04:00

Tags