defmodule CR do @moduledoc """ A little program to read a simple CSV file and summ all of the numbers along the row. Anything non-numeric is treated as 0. The file name is given on the command line Usage: elixir commread.ex filename author: gtowell created: August 2022 """ @doc """ A small function to process each line in the CSV file. Just sums up everything that can be parsed to an integer The return value from this function is nil and is unused as this function is run for its side effect """ def do_line(line) do String.split(line, ",") |> Enum.reduce(0, fn (value, acc) -> # Integer.parse returns :error on failure # Use case command to handle expected and error # note that _ will match to anything so :error matches case Integer.parse(value) do {ival, _rr} -> acc+ival _ -> acc end end) |> IO.puts end @doc """ read a file given on the command line Pass that file off, after first splitting it into a list of the lines in the file, to a handler If there is more than one argument given on the command line all but the first is ignored. If none given, just a usage message """ def main do # Use case command to handle user not providing a file # name on the command line. In that case the list from # argv has only one item so it does not match [h|_] # _ matches anything so when no command line param # print out a usage message case System.argv() do [h|_] -> {:ok, txt} = File.read(h) String.split(txt, "\n") |> Enum.each(fn v -> do_line(v) end) _ -> IO.puts "Usage: elixir commread.ex filename" end end def main2() do IO.inspect(System.argv()) end end CR.main2 #CR.main