fork download
  1. # getopt
  2.  
  3. BEGIN { msg = "usage: [-befhmn] [-D string]"
  4. print "There are", getopt("befhmnD:", msg), "options."
  5. for (flag in OPTS) { print flag, OPTS[flag] } }
  6.  
  7. function getopt(defn, msg, n, i, flag, rest) {
  8.  
  9. # collect flag/value pairs in OPTS,
  10. # remove from ARGV, and return count
  11.  
  12. # initialize i, loop runs forever
  13. for (i = 1; ;) {
  14.  
  15. # stop at end of arguments
  16. if (i == ARGC) { return n+0 }
  17. if (ARGV[i] == "--") { ARGV[i] = ""; return n+0 }
  18. if (ARGV[i] == "") { i++; continue }
  19. if (substr(ARGV[i],1,1) != "-") { return n+0 }
  20.  
  21. # found argument; parse flag from rest of string
  22. flag = substr(ARGV[i],2,1); rest = substr(ARGV[i],3)
  23.  
  24. # argument requires an associated value
  25. if (index(defn, flag ":") > 0) {
  26. if (rest != "") { # value in same argument as flag
  27. OPTS[flag] = rest; ARGV[i] = ""; i++; n++ }
  28. else if (i < ARGC) { # value in next argument
  29. OPTS[flag] = ARGV[i+1]; ARGV[i] = ARGV[i+1] = ""
  30. i += 2; n++ }
  31. else { print "ERROR: " flag " flag requires value " \
  32. ": " msg | "cat 1>&2"; exit 1 } }
  33.  
  34. # argument has no associated value
  35. else if (index(defn, flag) > 0) {
  36. if (rest != "") {
  37. OPTS[flag] = ""; ARGV[i] = "-" rest; n++ }
  38. else { OPTS[flag] = ARGV[i] = ""; n++ } }
  39.  
  40. # unrecognized flag
  41. else { print "ERROR: unrecognized flag " flag \
  42. ": " msg | "cat 1>&2"; exit 1 } } }
Success #stdin #stdout 0s 4388KB
stdin
Standard input is empty
stdout
There are 0 options.