Skip to content

Commit da6f727

Browse files
committed
Cookbook recipe to parse command-line arguments with stdlib only
1 parent f0ce6b7 commit da6f727

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
---
2+
packages: []
3+
---
4+
(* `Sys.argv` is the command-line arguments as an array of strings
5+
([standard library documentation](https://ocaml.org/manual/5.3/api/Sys.html#VALargv)).
6+
Here we print each argument with its corresponding index in the array. *)
7+
let simplest_parser () =
8+
Sys.argv
9+
|> Array.to_list
10+
|> List.iteri (Printf.printf "argument %d: %s\n")
11+
12+
13+
(* `Arg` is a module for parsing command-line arguments, and it is part of
14+
OCaml's standard library
15+
([documentation](https://ocaml.org/manual/5.3/api/Arg.html)).
16+
In this function we define the structure of the command-line arguments we
17+
expect, the argument types types and their documentation. This is basically
18+
the same function defined in the module's documentation.
19+
20+
*)
21+
let arg_module_parser () =
22+
let usage_msg =
23+
"mycmd [--verbose] <file1> [<file2>] ... -o <output>"
24+
and verbose = ref false
25+
and input_files = ref []
26+
and output_file = ref "" in
27+
(* This function is called once for each anonymous argument. *)
28+
let anonymous_args_f filename =
29+
input_files := filename :: !input_files
30+
(* The spec list defines argument keywords, "setter" functions to handle the
31+
values, and their corresponding documentation. *)
32+
and spec_list =
33+
[("--verbose", Arg.Set verbose, "Output debug information");
34+
("-o", Arg.Set_string output_file, "Set output file name")]
35+
in
36+
Arg.parse spec_list anonymous_args_f usage_msg;
37+
Printf.printf "verbose: %b\n" !verbose;
38+
Printf.printf "input files: %s\n"
39+
(!input_files |> String.concat ", ");
40+
Printf.printf "output file: %s\n" !output_file
41+
42+
(* Given a command-line like `mycmd --verbose file1 -o /tmp/out`, we should
43+
expect the following output:
44+
45+
```
46+
=== Simplest parser ===
47+
argument 0: mycmd
48+
argument 1: --verbose
49+
argument 2: file1
50+
argument 3: -o
51+
argument 4: /tmp/out
52+
53+
=== Arg.parse ===
54+
verbose: true
55+
input files: file1
56+
output file: /tmp/out
57+
``` *)
58+
let () =
59+
print_endline "=== Simplest parser ===";
60+
simplest_parser ();
61+
62+
Printf.printf "\n%!";
63+
64+
print_endline "=== Arg.parse ===";
65+
arg_module_parser ()

0 commit comments

Comments
 (0)