Clojure: Command Line Processing

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;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 [&amp; args]
  (with-command-line args
    "Get csv file name"
    [[file-name ".csv file name" "resultset.csv"]]
    (println "filename:" file-name)
    (process-file file-name)))
Advertisements

Leave a comment

Filed under Clojure

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s