read-line in common lisp
I want to read input from STDIN, and just read what it is: if input is a list, then what is read is a list. However, the read-line function seems always return a string! For example: in clisp interactive envrironment:
(read-line)
I input:
("(define M ::int )" "(define X ::int )")
The it will give me back a string:
"(\"(define M ::int )\" \"(define X ::int )\")" ;
What I want is still the original list:开发者_如何转开发 ("(define M ::int )" "(define X ::int )")
So How to make the read-line read in what the input it was?
Try simply with:
(read)
That should work
(let ((a read)))
(eval a))
(+ 2 2 2)
=> 6
there's a reason they call it a READ EVAL PRINT LOOP.
(read-line)
returns a string terminated by a new-line.
(read)
is the Lisp parser.
Letting the user enter a Lisp expression is certainly risky. Therefore, I would protect the read function by wrapping it inside an ignore-errors:
(ignore-errors (read))
This way, if the user enters e.g. ")" (without the quotes), the interpreter will not enter the debug loop, but simply print an error message and return nil.
As others have pointed out, (read)
does what you need. Here's why: READ
takes an optional argument specifying the input stream from which to read. It defaults to *STANDARD-INPUT*
, designating STDIN, which is why it'll work without arguments, but you could specify other streams to read from (such as a file). E.g., (with-open-file (s path) (read s))
.
精彩评论