From gawk manual

Because some built-in functions (e.g. match, split, sub) accept regexp constants as arguments, confusion can arise when attempting to use regexp constants as arguments to user-defined functions. For example:

function mysub(pat, repl, str, global)
if (global)
gsub(pat, repl, str)
sub(pat, repl, str)
return str
text = "hi! hi yourself!"
mysub(/hi/, "howdy", text, 1)

In this example, the programmer wants to pass a regexp constant to the user-defined function mysub(), which in turn passes it on to either sub() or gsub(). However, what really happens is that the pat parameter is assigned a value of either one or zero, depending upon whether or not $0 matches /hi/. gawk issues a warning when it sees a regexp constant used as a parameter to a user-defined function, because passing a truth value in this way is probably not what was intended.

  1. How can I pass a regular expression constant as an argument to a function, so that the function can receive the argument as a regular expression instead of a truth value?

    In other word, before a regular expression constant is passed into a function, how can I prevent it from being evaluated as a string matching expression, and ensure it being treated as what it is?

  2. How can regular expression constants be passed to those builtin functions (e.g. match, split, sub) as regular expressions, without being evaluated as a string matching expression?


  • You can use quotes to pass regular expressions as arguments to functions: mysub("hi", "howdy", text, 1). Jul 19 '17 at 15:20

You should use quotes to pass values to function variables.

mysub( "hi", "howdy", text, 1)

Or using some other name for a variable:

thisarg = "hi"
mysub( thisarg, "howdy", text, 1)
  • This will fail for some cases, eg. when you want to pass a regex containing special characters. "warning: escape sequence \w' treated as plain w'"
    – patrik
    Mar 5 '19 at 12:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.