Skip to content

Instantly share code, notes, and snippets.

@AlchemistCamp
Last active June 25, 2018 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlchemistCamp/effe41619209cb73d4a5b17b9d69388c to your computer and use it in GitHub Desktop.
Save AlchemistCamp/effe41619209cb73d4a5b17b9d69388c to your computer and use it in GitHub Desktop.
Episode 5 source code (challenge 2)
filename =
IO.gets("File to count the words from (h for help):\n")
|> String.trim
if filename == "h" do
IO.puts """
Usage: [filename] -[flags]
Flags
-l displays line count
-c displays character count
-w displays word count (default)
Multiple flags may be used. Example usage to display line and character count:
somefile.txt -lc
"""
else
parts = String.split(filename, "-")
filename = List.first(parts) |> String.trim
flags = case Enum.at(parts, 1) do
# set only "w" flag if none were set
nil -> ["w"]
chars -> String.split(chars, "") |> Enum.filter(fn x -> x != "" end)
end
body = File.read! filename
lines = String.split(body, ~r{(\r\n|\n|\r)})
words =
String.split(body, ~r{(\\n|[^\w'])+})
|> Enum.filter(fn x -> x != "" end)
chars = String.split(body, "") |> Enum.filter(fn x -> x != "" end)
Enum.each(flags, fn flag ->
case flag do
"l" -> IO.puts "Lines: #{Enum.count(lines)}"
"w" -> IO.puts "Words: #{Enum.count(words)}"
"c" -> IO.puts "Chars: #{Enum.count(chars)}"
_ -> nil
end
end)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment