Search code examples
elixir

Error message about 2nd argument to Enum.to_list


I have a file, where erach line consists of "fields" separated by semicolons, for instance

AAA;BBBB;CCC
XXX;YY;ZZZ

The fields themselves contain neither a semicolon nor a newline character. There is no fancy quoting going on, so the file is a bit like a "simple" CSV file without any quoting and escape characters.

My goal is to turn this file into a list of lists, like this:

[["AAA", "BBBB", "CCC"], ["XXX", "YY", "ZZZ"]]

My approach in my Elexir script went like this:

File.stream!(cfile)
|> Stream.map(fn (line) -> String.split(line, ';') end)
|> Enum.to_list()
|> IO.puts()

(The purpose of the final IO.puts is just for debugging. In the end, the resulting list will be processed somehow).

My understanding of my script is:

  • The first line produces a Stream for this file.
  • The second line splits every line from this stream and the whole operation yields an Enumerable of lists
  • The third line turns the Enumerable of lists into a list of lists.

Running this script throws an error

* 2nd argument: not a valid pattern

and the line number for the error message points to the line containing Enum.to_list. This function doesn't even have a 2nd argument! String.split would have two arguments, but this is in the line before, and the arguments to split look fine for me.

Could someone kindly explain, what's going wrong here? Or is my approach to process a file line by line flawed in some fundamental way?


Solution

  • You provided a charlist ';' rather than a string ";" as the second argument to String.split/3:

    iex(1)> String.split("AAA;BBBB;CCC", ';')
    ** (ArgumentError) errors were found at the given arguments:
    
      * 2nd argument: not a valid pattern
    

    vs.

    iex(2)> String.split("AAA;BBBB;CCC", ";")
    ["AAA", "BBBB", "CCC"]