LISP - Converting a string with the representation of an array to an array
Asked Answered
R

1

5

I have a file which has an bi-dimensional array in each line. I'm having trouble finding a way of parsing the file into actual arrays and them putting them in a list.

the file looks like this, the arrays are in different lines, even though it does not seem to: file with matrixes

Radiobiology answered 8/12, 2015 at 12:17 Comment(0)
C
9

You just open the file for reading using with-open-file and then use the function read as often as you would like or as often as there are arrays. Each read returns an array. Using loop you can collect them into a list.

Basically something like this:

(with-open-file (s filename)
  (let ((*read-eval* nil))
    (loop with eof = '#:eof
          for object = (read s nil eof)
          until (eq object eof)
          collect object)))

Note also that it does not matter whether each array is on its own line. It would still work if they are on one line. A newline between expressions is just whitespace for the Lisp reader.

Crossarm answered 8/12, 2015 at 12:34 Comment(4)
Thank you! so much easier that I thought :)Radiobiology
@LidiaFreitas: that's because the array is already printed in Common Lisp syntax. :-)Crossarm
… and always bind *read-eval* to nil before reading from untrusted sources.Gynecology
@Svante: good advice. I've added that. That's probably where the language should be changed, or where a standard macro with-secure-io-syntax (as opposed to cl:with-standard-io-syntax) is needed.Crossarm

© 2022 - 2024 — McMap. All rights reserved.