Created
January 25, 2019 09:25
-
-
Save y2q-actionman/553a490072d7c388168e81a7b8a7b274 to your computer and use it in GitHub Desktop.
progv を使って csv ヘッダを変数名として取り込んでループ回す
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(in-package :cl-user) | |
(ql:quickload "split-sequence") | |
(defparameter *test-file* "/tmp/progv_test.csv") | |
(defun write-test-csv () | |
(with-open-file (out *test-file* :direction :output :if-does-not-exist :create | |
:if-exists :rename) | |
(format out "col1,col2,col3~%") | |
(format out "100,200,300~%") | |
(format out "a,b,c~%"))) | |
(defun csv-callback () | |
(declare (special |col1| |col2| |col3|)) | |
(format t "~&col1: ~A, col2: ~A, col3: ~A~%" | |
|col1| |col2| |col3|)) | |
(defun read-csv-and-use-callback (&optional (func #'csv-callback)) | |
(assert (probe-file *test-file*)) | |
(with-open-file (in *test-file* :direction :input) | |
(let* ((header (read-line in)) | |
(cols-list (split-sequence:split-sequence #\, header)) | |
(cols-symbols (mapcar #'intern cols-list))) | |
(loop for line = (read-line in nil nil) | |
while line | |
do (let ((data (split-sequence:split-sequence #\, line))) | |
(progv cols-symbols data | |
(funcall func))))))) | |
#| | |
CL-USER> (progn (write-test-csv) | |
(read-csv-and-use-callback)) | |
col1: 100, col2: 200, col3: 300 | |
col1: a, col2: b, col3: c | |
NIL | |
|# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment