Clojure: Command Line ProcessingPosted: June 20, 2011
If I have any complaints about Clojure documentation it’s lack of I/O basics in the core documentation, like reading and writing files. This is a small matter, though, because there are lots of folks out there talking about those issues, like http://tech.puredanger.com/2010/02/25/clojure-command-line-options/.
I’ve modified my own .csv reading application to take a file name from the command line:
(ns test-csv (:gen-class) (:use clojure.contrib.command-line) (:use clojure-csv.core))</code> (defn process-file "Process csv file and prints first item in every row" [file-name] (let [data (slurp file-name) rows (parse-csv data)] (dorun (map #(println (first %)) rows)))) (defn -main [&amp; args] (with-command-line args "Get csv file name" [[file-name ".csv file name" 1]] (println "file-name:", file-name) (if file-name (process-file "resultset.csv") (process-file file-name))))
As the Google Clojure Users Group pointed out, there is a better way to get the default file on the command line, in case none is specified:
(defn -main [& args] (with-command-line args "Get csv file name" [[file-name ".csv file name" "resultset.csv"]] (println "filename:" file-name) (process-file file-name)))