Command Line Arguments in Clojure
In Clojure, command-line arguments are accessed through the *command-line-args*
special variable. Here’s how we can work with command-line arguments:
The *command-line-args*
sequence provides access to raw command-line arguments. Note that unlike in some other languages, this sequence does not include the program name as its first element.
In our example, we’re using *file*
to get the name of the current file, which is similar to getting the program name. We then use cons
to prepend this to the arguments list to create args-with-prog
.
You can get individual args with normal indexing using the nth
function. Remember that Clojure uses zero-based indexing.
To experiment with command-line arguments, it’s best to create a script or compile to a JAR file first. Here’s how you might run it:
In this example, we’re using clj
to run our Clojure program directly. The -m
flag specifies the namespace to use as the entry point.
Next, we’ll look at more advanced command-line processing with option parsing libraries in Clojure.