Simple string splitting, newbie needs help

Hey I’m new to Elixir and trying to work through “Advent of code” in order to get a better understanding of the language. Right now I’m having difficulties sorting out newline characters in a string and converting that string into a list.

defmodule One do 

    def readme(filename) do 
        my_text = File.read(filename)
        String.split(my_text, ~r{\n})
    end

end 

I know this might just be terrible elixir but could someone help me understand why it is not correctly splitting the string by newline and moving it into a list ?

I keep getting this error:

Attempted function clauses (showing 3 out of 3):

    def split(string, %Regex{} = pattern, options) when is_binary(string) and is_list(options)
    def split(string, "", options) when is_binary(string) and is_list(options)
    def split(string, pattern, options) when is_binary(string) and is_list(options)

(elixir 1.12.2) lib/string.ex:473: String.split/3

Thank you !

File.read/1 will return a tuple {:ok, contents}, not a string. You are feeding this tuple to String.split/2, but that will not work.

2 Likes

right okay that makes more sense, thank you.

Yes…

You should have

{:ok, mytext} = ...
# or
my_text = File.read!(...)

And no need to use ~r{\n} later

String.split(my_text)
2 Likes

perfect, the File.read!(…) makes sense to me

The Elixir way would be :slight_smile:

filename
|> File.read!()
|> String.split()
5 Likes

thats way sexier than mine, ty :wink:

1 Like

I’m not sure this will do what the Original Poster wants because that is not equivalent. String.split/1 will split on all whitespace characters instead of just newlines.

Compare the output of these two expressions:

iex(3)> String.split(" foo   bar\nbaz")
["foo", "bar", "baz"]
iex(4)> String.split(" foo   bar\nbaz", "\n")
[" foo   bar", "baz"]
2 Likes

You are right, it splits on whitespace and it’s not what the OP wanted :slight_smile:

filename
|> File.read!()
|> String.split(~r{\n})
2 Likes

For Advent of Code puzzle input, you will also need to include the trim: true option, because the last character of the file will be a newline.

2 Likes