为什么外部区域中定义的变量在内部区域不可用?

时间:2015-01-15 13:26:47

标签: clojure

我有以下代码,在第二行我定义了file-fields-in-keyword,但它只在第3行,第10行和第24行可用,它打印为nil。但是为什么第10,24行看到nil而第3行看到非零值?我希望它们是相同的

(defn load-file-to-database [file-name file-id constraints-map auto-creation-config delimiter]
  (let [file-fields-in-keyword (get-file-header-as-key-word file-name)]
    (println file-fields-in-keyword)
    (with-open [rdr (io/reader file-name)]
      (doseq [chunk (partition-all 10000  (map-indexed
                                           (fn [index line] (str file-id delimiter (inc index) delimiter line))
                                           (line-seq rdr)
                                           ))]
        (println (count chunk))
        (println file-fields-in-keyword)   ;; it prints nil
        (println (first chunk))
        (let [rows (map #(clojure.string/split %  #",") chunk)
              rows-map (map #(zipmap file-fields-in-keyword %) rows)
              rows-after-validation (map #(process-row % constraints-map auto-creation-config) rows-map)
              valid-records (valid-lines rows-after-validation)
              invalid-records (invalid-lines rows-after-validation)
              ]

          (println (count valid-records))
          (println (count invalid-records))
          (println (first valid-records))
          (println (first invalid-records))
          (println "xxx")
          (println file-fields-in-keyword) ;; it prints nil
          (apply (partial j/insert! postgres-db  'test_clojure file-fields-in-keyword) valid-records)
          )))
    )
  )

(defn get-file-header-as-key-word [file-name]
  (with-open [rdr (io/reader file-name)]
    (println (map keyword (str/split (str row_number "," "file_id" "," (first (line-seq rdr))) #",")))
    ))


(load-file-to-database file-name 100 constraints-map auto-creation-config ",")

1 个答案:

答案 0 :(得分:2)

你是对的,所有三个值应该是相同的。

函数get-file-header-as-key-word返回的值始终为nil,因为println始终返回该值,因此对println的所有三次调用都应打印为nil file-fields-in-keyword的值。

要从nil功能中获取非get-file-header-as-key-word值,您需要移除对println的调用。这应该会导致printlnload-file-to-database的所有输出与非nil值相同。