Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

awk

gawk

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.

like image 573
joelparkerhenderson Avatar asked Dec 25 '22 13:12

joelparkerhenderson


1 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
like image 124
Ed Morton Avatar answered Feb 01 '23 06:02

Ed Morton