Reputation: 857
I have a function
(defun read-as-list (filename)
(defparameter parlist(list nil) )
(let ((in (open filename :if-does-not-exist nil)))
(when in
(loop for line = (read-line in nil)
while line do
(defparameter mylist line)
(push mylist (cdr (last parlist)))
;(append parlist (list mylist))
;(print mylist)
;(format t "~a~%" line)
)
(close in)
)
)
(print parlist)
(return-from read-as-list parlist)
)
which simply takes a file name and reads it into a nested list and returns the list
I call it in the down function like:
(defun test_on_test_data ()
(print "....................................................")
(print "Testing ....")
(print "....................................................")
(let (con (read-as-list "document1.txt"))
(print con)
)
)
(test_on_test_data)
in the function test-on-test-data
, con
prints nil
and it does not call the function read-as-list
instead of printing the content of the files as list it prints nil
.
can someone please help me out on this.
Upvotes: 1
Views: 1155
Reputation: 38967
Here is an example function that you can use to test how to iterate over lines in a file. It takes a pathname designator and a callback function, and execute the function for all lines in a file. The function must accept a single parameter, the line being read.
(defun maplines (function path)
(with-open-file (in path)
(loop for line = (read-line in nil nil)
while line
do (funcall function line))))
Note how the code is indented, and how the opening and closing of the file is handled using with-open-file
.
Also, there is no defparameter
inside the function's body since that form is used to declare global variables.
There is no need to use return since the last value in the function body is automatically the value of the function call.
Then, you can for example call it as follows:
(maplines #'print "/tmp/test.data")
Unlike in your code, if the file does not exist, an error will be signaled. In your case you silently ignored errors by giving nil
and doing nothing on a null stream.
Finally, all you need is to use a function that stores the lines being read. Or if you don't know yet how to do that, modify the above snippet to remove the call to funcall and use collect
in the loop. You will get a list of all lines.
Upvotes: 1