joelparkerhenderson
joelparkerhenderson

Reputation: 35483

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

I'm seeking a way to call an awk function by name, i.e. by using a string that is user input.

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

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

... with any kind of way to dispatch to the function by using the string name something like this:

send(text, x)

In other languages, this kind of effect is sometimes described as reflection, or message sending, or dynamic dispatch, or getting a function pointer by name.

I'm looking for a way to do this using gawk and ideally also using POSIX portable awk.

Upvotes: 5

Views: 799

Answers (2)

Ed Morton
Ed Morton

Reputation: 204258

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

Upvotes: 10

Zombo
Zombo

Reputation: 1

#!/usr/bin/awk -f
func alpha() {
  print "bravo"
}
BEGIN {
  charlie = "alpha"
  @charlie()
}

Output:

bravo

GNU awk - Git Repositories

Upvotes: 3

Related Questions