Input and Command-Line Arguments
Prerequisites: Functions, Conditionals
Command-line arguments
Arguments after the file name arrive in *command-line-args*, a
sequence of strings (or nil when there are none):
;; illustrative — run as: clj -M greet.clj Ada 3
(let [[name times] *command-line-args*
name (or name "world")
times (if times (parse-long times) 1)]
(dotimes [_ times]
(println (str "Hello, " name "!"))))
Hello, Ada!
Hello, Ada!
Hello, Ada!
parse-long (Clojure 1.11+) turns a string into a number, returning
nil if it isn't one. parse-double and parse-boolean work the same
way.
Reading from the keyboard
;; illustrative — needs keyboard input
(print "What is your name? ")
(flush)
(def user-name (read-line))
(print "How old are you? ")
(flush)
(def age (parse-long (or (read-line) "")))
(if age
(println (str "Hi " user-name ", next year you'll be " (inc age) "."))
(println "That isn't a number."))
What is your name? Ada
How old are you? 36
Hi Ada, next year you'll be 37.
read-linereturns the next line, ornilat the end of input.printdoesn't flush the output, so call(flush)before waiting for input, or the prompt may not appear.
Reading piped input
;; illustrative — run as: cat data.txt | clj -M count.clj
(let [lines (line-seq (java.io.BufferedReader. *in*))]
(println (count lines) "lines"))
Environment variables and exit codes
(println (some? (or (System/getenv "HOME") (System/getenv "USERPROFILE"))))
(println "mode:" (or (System/getenv "APP_MODE") "development"))
(println (parse-long "42") (parse-long "4x2") (parse-double "2.5"))
true
mode: development
42 nil 2.5
(System/exit 1) ends the program with an error code that shells and
CI systems can detect. Level 3 shows clojure.tools.cli for options
like --verbose.