[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Should nextfile in BEGINFILE skip ENDFILE?
From: |
Ed Morton |
Subject: |
Re: Should nextfile in BEGINFILE skip ENDFILE? |
Date: |
Sun, 15 Nov 2020 11:42:43 -0600 |
User-agent: |
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Thunderbird/78.4.3 |
On 11/15/2020 4:13 AM, arnold@skeeve.com wrote:
Hello Ed.
With |gawk|, |nextfile| is useful inside a |BEGINFILE| rule to skip
over a file that would otherwise cause |gawk| to exit with a fatal
error. In this case, **|ENDFILE| rules are not executed**.
Read that a little closer. In the case where gawk would normally
exit with an error, ENDFILE is skipped.
$ ./gawk 'BEGINFILE{print "a"; nextfile} ENDFILE{print "b"}' /no/such/file
a
The ENDFILE is not executed.
I thought that was just saying that given nextfile exists you could write:
BEGINFILE {
if ( (getline < FILENAME) < 0 ) {
nextfile
}
}
or similar to test if you can open the current file, I didn't get that
the behavior would automatically change if an error occurred.
I have to say I do wish that wasn't the case and nextfile simply behaved
the same in a BEGINFILE as anywhere else and caused ENDFILE to be
evaluated as it's not clear why skipping ENDFILE would always be
desirable, it's not obvious why puting a nextfile in a BEGINFILE would
be related to handling of errors opening files, and it's easy to handle
errors opening files using a getline without this, e.g. if nextfile
behaved the same in BEGINFILE as everywhere else and I wanted to handle
file opening errors gracefully I could just write this clear, brief,
simple code:
BEGINFILE {
bad_file = 0
if ( (getline < FILENAME) < 0 ) {
print FILENAME, "is a bad file"
bad_file = 1
nextfile
}
}
ENDFILE {
if ( !bad_file ) {
do stuff
}
}
I think I need to fix this sentence, in the previous paragraph:
| In @command{gawk}, execution of @code{nextfile} causes additional things
| to happen: any @code{ENDFILE} rules are executed if @command{gawk} is
| not currently in an @code{END} or @code{BEGINFILE} rule,
to remove the BEGINFILE rule bit.
Agreed given what I now know.
Thanks,
Ed.
Thanks.
Arnold