2
\$\begingroup\$

I've written a simple grep program as my first foray into Elixir. Could you please suggest some ways in which the code could make better use of the language?

defmodule Exgrep do

  def exgrep(path \\ ".", substring) do
    case File.ls(path) do
      {:ok, ls} ->
        Enum.map(ls, fn new_path -> exgrep Path.join(path, new_path), substring end)
      {:error, _} ->
        exgrep_file path, substring
    end
  end

  def exgrep_file(path, substring) do
    case File.open(path, [:read]) do
      {:ok, f} -> line_grep f, substring, path
      {:error, _} -> nil
    end
  end

  def line_grep(file, substring, path) do
    case IO.read(file, :line) do
      :eof -> nil
      line ->
        if (String.contains?(line, substring)) do
          IO.puts "LINE: #{String.trim(line)} IN: #{path}"
        end
        line_grep file, substring, path
    end
  end

end

Exgrep.exgrep ".", "par"

Output:

LINE: sparrow IN: ./animals/birds/city.txt
LINE: leopard IN: ./animals/other.txt
LINE: Exgrep.exgrep ".", "par" IN: ./exgrep.ex
[nil, [[nil], nil], nil, nil]
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.