You are not logged in.

#1 2012-07-14 18:28:34

schalox
Member
From: Finland
Registered: 2011-05-10
Posts: 21

[SOLVED] Custom function returns syntax error in awk

Hi, any idea why this returns syntax error in gawk 4.0.1?

#!/bin/awk -f

BEGIN {
    function new() {
        print "kl"
    }
    new
}

Output:

awk: ./test:4:     function new() {
awk: ./test:4:     ^ syntax error
awk: ./test:4:     function new() {
awk: ./test:4:                    ^ syntax error

Moving the curly bracket (after function) into its own row returns this:

awk: ./test:4:     function new()
awk: ./test:4:     ^ syntax error

Removing BEGIN didn't fix it, nor did changing the function name.
I've read the relevant part of the man page and the gawk user guide and I've searched DuckDuckGo and the forums for an answer, but so far I've found nothing to indicate what could be wrong.

Last edited by schalox (2012-07-14 21:07:08)

Offline

#2 2012-07-14 18:41:04

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 30,330
Website

Re: [SOLVED] Custom function returns syntax error in awk

I don't think function declarations can go inside rules (eg BEGIN).  Declare the function before the BEGIN block and you should be fine.


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#3 2012-07-14 18:49:15

schalox
Member
From: Finland
Registered: 2011-05-10
Posts: 21

Re: [SOLVED] Custom function returns syntax error in awk

Thanks for the quick reply. I tried this, it returned the same error:

#!/bin/awk -f

{
    function test_function() {
        print "kl"
    }
}
BEGIN {
    test_function
}

EDIT: Okay you're totally right. Just realised the function was still declared inside a rule in the previous attempt. I tried this and it worked as it should:

#!/bin/awk -f

function test_function()
{
    print "kl"
}

BEGIN {
    test_function()
}

Thanks for the help, Trilby.

Last edited by schalox (2012-07-14 21:04:51)

Offline

Board footer

Powered by FluxBB