What you have would be fine, though it's often written as:
function operation1(line) {
# code for operation 1
}
function operation2(line) {
# code for operation 2
}
mode == "op1" { operation1($0); next }
mode == "op2" { operation2($0); next }
{ print } # default action
You can alternatively use indirect function calls with GNU awk to map the value of mode directly to the name of a function, e.g.:
BEGIN {
fun = "operation" gensub(/op/,"",1,mode)
if ( ! (fun in FUNCTAB) ) {
fun = "operation_default"
}
}
function operation1(line) {
# code for operation 1
}
function operation2(line) {
# code for operation 2
}
function operation_default(line) {
# default action
}
{ @fun($0) }
Here's the problem with the above though - awk is a text processing tool. It's main purpose is to read input and do things given various values in the input. So when you write code like any form of:
mode == "op1" { operation1($0); next }
mode == "op2" { operation2($0); next }
it's being executed within awks implied while-read loop as:
while (read $0) {
mode == "op1" { operation1($0); next }
mode == "op2" { operation2($0); next }
}
so mode == "op1" is being tested for every line of the input and then the associated function operation1($0) is being called for every line of the input when you call the script with -v mode="op1". Given that, what would operation1() actually do?
In C or some other procedural language you might write the equivalent of:
if (mode == "op1") { operation1(); next }
if (mode == "op2") { operation2(); next }
and then you'd write operation1() as:
operation1() {
while (read line) {
do operation1 stuff
}
}
but then the while-read loop that awk provides at the outer level is written at the lower level within each function. You can implement that in awk with a getline loop but that has caveats/issues, see http://awk.freeshell.org/AllAboutGetline.
So, while you can write functions to be called as the OP shows, their applicability tends to be quite limited given awks role as a text-processing tool doing things within a built-in while-read loop (where each mutually-exclusive function called from the highest level tends to be "do something with the current record") rather than a general purpose programming language (where each mutually-exclusive function called from the highest level tends to be "do something with the entire input").
One example of the kind of use-case for such a program structure in awk might be converting input to some other form of output one record at a time, e.g.:
function prtCsv( i) {
for ( i=1; i<=NF; i++ ) {
gsub(/^"|"$/, "", $i)
gsub(/"/, "\"\"", $i)
printf("\"%s\"%s", $i, (i<NF ? "," : ORS)
}
}
function prtTree( i) {
for ( i=1; i<=NF; i++ ) {
print "%*s%s\n", (i-1)*4, "", $i
}
}
mode == "csv" { prtCsv(); next }
mode == "tree" { prtTree(); next }
{ print } # default action