ClojureDocs

Nav

Namespaces

read-line

clojure.core

Available since 1.0 (source)
  • (read-line)
Reads the next line from stream that is the current value of *in* .
4 Examples
user=> (read-line)
line to be read      ;Type text into console
"line to be read"
;; (flush) is needed to display print values.
;; Otherwise the print value stays buffered until you hit enter.
user=> (do (print "What's your name? ") 
           (flush) 
           (read-line))
What's your name? Clojure
"Clojure"
(println "Enter something> ")
(def x (read-line))
(println (str "You typed \"" x "\""))
;; Example of a tiny menu system. Usage:

(menu {:prompt "Which database" 
       :options ["Localhost" "Remote" {:id "o" :text "Other"}]})

;; Implementation
(require '[clojure.string :as str])

(defn menu [{:keys [prompt options]}]
  (let [options       (map (fn [o idx]
                             (if (string? o)
                               {:id (str (inc idx)) :text o}
                               o)) options (range))
        valid-options (set (map :id options))]
    (loop []
      (when prompt
        (println)
        (println prompt)
        (println))
      (doseq [{:keys [id text]} options]
        (println (str " [" id "]") text))
      (println)
      (println "or press <enter> to cancel")

      (let [in (str/trim (read-line))]
        (cond (= in "")
              :cancelled

              (not (valid-options in))
              (do
                (println (format "\n-- Invalid option '%s'!" in))
                (recur))

              :else
              (first (filter #(= in (:id %)) options)))))))
See Also

Flushes the output stream that is the current value of *out*

Added by kimtg
1 Note
    By , created 7.5 years ago

    Be aware that read-line uses Java’s BufferedReader’s .readLine method that itself uses an internal buffer of either 4k or 8k. That causes (read-line) to return a truncated string if you try to read a large line.