Command Line Arguments in OCaml
Command-line arguments are a common way to parameterize execution of programs. For example, ocamlc -o hello hello.ml
uses -o
, hello
, and hello.ml
as arguments to the ocamlc
program.
To experiment with command-line arguments, it’s best to compile the program first:
In OCaml, we use the Sys.argv
array to access command-line arguments. The first element (Sys.argv.(0)
) is the program name, and subsequent elements are the arguments passed to the program.
We convert the array to a list for easier manipulation. The List.tl
function is used to get all elements except the first one (the program name).
Individual arguments can be accessed using array indexing, as shown with Sys.argv.(3)
.
The Printf.printf
function is used to print the results, with String.concat
joining the list elements into a single string.
Next, we’ll look at more advanced command-line processing with command-line parsing libraries in OCaml.