Our second project is a simple command line script that counts the words in a file, much like the Unix command
We'll see some differences between writing Elixir modules and one-off scripts and we'll see how to read a file. The most difficult part of the lesson is deciding how to split the file into words. We'll get a taste of the both the joy and the terror of regular expressions in the process.
Source code for this episode
IO.getsto ask user the name of a file to open
String.trimto get rid of trailing enter they press
Split the string into words with
String.splitand a regular expression
Filter out non words with
Count the words with
The middle portion of the video also includes a detour showing some basics of regex and working with them in Elixir.
mix utility is not used at all in this lesson. Neither is
escript. Both are covered in a future lesson but there's some value in working with the very basics first, so that's what we did.
See if you can extend the script build in this lesson so that the user can optionally count the number of lines or characters a file instead of the number of words.
Hint: The challenge in this lesson will be much easier if you look at the docs for Enum and see what Enum.each and Enum.at do.
@abdulrahman, I have this in my VS Code
settings.json(open it with cmd/ctrl + ,)
good lecture by the way auto formatting when save doesn't work for me i need to click Alt + Shift + F
For those who are curious about
Code.load_file/2being deprecated, don't worry! It won't be removed until Elixir 2.0, which isn't even on the road map and Jose has said Elixir is "done".
Going forward, the function is renamed to
Code.compile_file/2, and the usage is still the same. Note that the 2nd argument defaults to
nil, which is why it can be called with just one argument as in this video.
Nice one! thanks @alchemist
Great video! To accelerate testing, you can use echo "word_count.exs" | elixir word_count.exs to not have to rewrite "word_count.exs" to the program every time.
@zababa: I like the way you think! If you look closely at the video, you'll see that the terminal was Power Shell and not bash or similar, though. I think this would be the command: