Function to read next non blank line from a file

(Very experienced procedural programmer trying to learn elxir, so please excuse noob questions.)

Following on from my ‘how to read file line by line’ post.

Simple need, a function that returns the next non blank line from a file. Its already open, so I need pass the io returned from open as an arg. I know I need to recurse ( I think) but none of the ‘getting started with recursion in elixir’ articles help.

Non blank means len > 0 after strip all whitespace

1 Like

For these things you want to pattern match either by “\n” or ?\n

Also, before you start playing around with streams then I would recommend you to build a recursive function that walks the binary and accumulates the result to iodata.

It will teach you everything you’ll need to know and you can then apply it to streams.

sorry, my reference to prior post was misleading. I am not using streams. Just File.open and then IO.read(io, :line)

I am parsing line by line and need to ignore blank lines.

An example, or even a rough hint as to what the recursion would look like would really help.

Erlang has some nice docs: Constructing and Matching Binaries — Erlang System Documentation v28.0.2

In my post above I showed you how to match on newlines rather that be in a binary or an Erlang string aka charlist.

When you state that the line is blank I assume you mean that the line is just a new line: \n

its not the detection of blank line (I said what blank line means in this case in the question) I am stuck on, its the ‘looping’ . Anyway I asked gh copilot to do it for me, and I am embarrased that I couldnt work it out for myself

  def next_non_blank_line(io) do
    case IO.read(io, :line) do
      :eof ->
        :eof

      line ->
        if String.trim(line) == "" do
          next_non_blank_line(io)
        else
          line
        end
    end
  end

Yeah, you got it. Nothing to be embarrassed about, you’re learning a new language and a functional one.

Although, you can easily make the function branchless, not that you need it now, but I still recommend to take a look at the Erlang docs for building recursive functions.

Best of luck!

i want to get into good habits, how would you improve it, also pointers to recursion docs would be great, so many of them are either, factorial or similar things that I would have written recursively before.