Command Line Flags in Nim
Here’s the translation of the Go code to Nim, formatted in Markdown suitable for Hugo:
Our first program demonstrates how to use command-line flags in Nim. Command-line flags are a common way to specify options for command-line programs. For example, in wc -l
the -l
is a command-line flag.
import parseopt
import strutils
proc main() =
var
word = "foo"
numb = 42
fork = false
svar = "bar"
var p = initOptParser()
for kind, key, val in p.getopt():
case kind
of cmdLongOption, cmdShortOption:
case key
of "word": word = val
of "numb": numb = parseInt(val)
of "fork": fork = true
of "svar": svar = val
of cmdArgument:
echo "Argument: ", key
of cmdEnd: assert(false) # cannot happen
echo "word: ", word
echo "numb: ", numb
echo "fork: ", fork
echo "svar: ", svar
echo "tail: ", commandLineParams()[p.remainingArgs .. ^1]
main()
Nim provides a parseopt
module for parsing command-line options. We’ll use this module to implement our example command-line program.
In the main
procedure, we first declare variables with default values for our flags.
We then use initOptParser()
to create a parser object, and iterate over the command-line options using getopt()
. This allows us to handle both long and short options.
For each option, we check its key and update the corresponding variable. We also handle positional arguments and print them.
After parsing all options, we print out the final values of our variables, including any remaining arguments.
To experiment with this program, save it as command_line_flags.nim
and compile it:
$ nim c -r command_line_flags.nim
Try out the built program by giving it values for all flags:
$ ./command_line_flags --word=opt --numb=7 --fork --svar=flag
word: opt
numb: 7
fork: true
svar: flag
tail: @[]
Note that if you omit flags, they automatically take their default values:
$ ./command_line_flags --word=opt
word: opt
numb: 42
fork: false
svar: bar
tail: @[]
Trailing positional arguments can be provided after any flags:
$ ./command_line_flags --word=opt a1 a2 a3
word: opt
numb: 42
fork: false
svar: bar
tail: @["a1", "a2", "a3"]
Unlike Go’s flag package, Nim’s parseopt doesn’t automatically generate help text. You would need to implement this functionality yourself if desired.
If you provide an unrecognized flag, the program will ignore it:
$ ./command_line_flags --wat
word: foo
numb: 42
fork: false
svar: bar
tail: @[]
This example demonstrates basic command-line flag parsing in Nim. The language offers more advanced option parsing capabilities through additional libraries if needed.