September 17, 2019

As I have said previously on this blog, I’m not allowed to write Scheme code at work; it would never make it past code review. But I can write shell scripts, and Awk is a natural language to use in shell scripts, so lately I have been writing a lot of Awk programs.

I recently had occasion to write an Awk program that took command-line arguments, so naturally I googled “getopt.awk” and found an implementation in the Gnu Awk manual. But that version of getopt was very C-like and not at all Awk-ish, so I decided to write my own. My getopt function extracts command-line arguments into an associative array OPTS that has the flag as its key and the value associated with the flag as its value; the value is null if the flag has no associated value. The getopt function takes two arguments — a string defining the available flags, in the same format as the C getopt function, and a string containing a message to be printed on error — and returns the number of arguments found.

Your task is to write a getopt function for your favorite langauge; if your language already provides command-line argument handling, write a version for Awk. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

<span>%d</span> bloggers like this: