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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With