piquet00
piquet00

Reputation: 31

AWK user-defined function - a new syntax?

When looking for a quick way of right trimming a text string, I found the following wiki page:

Wiki trimming page

In the chapter about AWK it gives 2 sets of examples:

ltrim(v) = gsub(/^[ \t]+/, "", v)

rtrim(v) = gsub(/[ \t]+$/, "", v)

trim(v)  = ltrim(v); rtrim(v)

or

function ltrim(s) { sub(/^[ \t]+/, "", s); return s }

function rtrim(s) { sub(/[ \t]+$/, "", s); return s }

function trim(s)  { return rtrim(ltrim(s)); }

The lower example is entirely familiar and works fine, but the first example looks different to anything I have seen in 20 years of AWK programming. It looks like a really useful quick way to define and use a function in one line. I can't get this syntax to work in GNU Awk 3.1.5 - so is it something which was introduced in a more recent version?

I would be grateful of a real working example if anyone is familiar with this syntax.

Upvotes: 3

Views: 632

Answers (2)

jlliagre
jlliagre

Reputation: 30843

My understanding is the first set of examples doesn't define a function but just tells that the (missing) ltrim(s) function can be replaced by gsub(/^[ \t]+/, "", v), etc.

gsub is unnecessary by the way, sub would be enough like it is in the function alternative.

Upvotes: 0

Dimitre Radoulov
Dimitre Radoulov

Reputation: 28000

I suppose this example is just wrong. The syntax

identifier(parameter) = ...

doesn't work with none of the variants I've tested: GNU awk (3, 4 - the latest for the moment), AT&T Bell's awk and mawk.

Just like calling an undefined function produces an error as expected as well.

Perhaps the author wanted only to illustrate the idea with pseudo-code?

Upvotes: 2

Related Questions