In Awk, how to call a function using a string name?

I am looking for a way to call a function awkby name, i.e. using a string entered by the user.

My goal is to replace a lot of code this way ...

if (text == "a") a(x)
if (text == "b") b(x)
if (text == "c") c(x)

... with any method of sending to a function using a string name something like this:

send(text, x)

In other languages, this effect is sometimes described as reflection, sending messages, or dynamically sending or receiving a function pointer by name.

I am looking for a way to do this using gawkand ideally also using POSIX portable awk.

+4
source share
2 answers

Using GNU awk 4.0 or later for Indirect function calls :

$ cat tst.awk
function foo() { print "foo() called" }
function bar() { print "bar() called" }

BEGIN {
    var = "foo"
    @var()

    var = "bar"
    @var()
}

$ awk -f tst.awk
foo() called
bar() called
+7
#!/usr/bin/awk -f
func alpha() {
  print "bravo"
}
BEGIN {
  charlie = "alpha"
  @charlie()
}

:

bravo

GNU awk - Git

+2

Source: https://habr.com/ru/post/1613134/


All Articles