We use our new-found powers to create a command line application that can be run directly from the shell and can handle arguments. Since we've already made a word count utility way back in the Word Count lesson, we'll use it as a starting point.
Elixir has a feature called
escript, which can be used to make more robust command line applications. The first thing we need to do is open up our
mix file and add an entry point for our script. Inside the project block, add:
escript: [main_module: WordCount.CLI],
Then we'll make a
WordCount.CLI file inside our
Escript entry points
Inside our new file we have to implement a
main function that takes args and does something based on the input. We'll use OptionParser to parse the arguments passed in from the command line. It's a convenient little utility that extracts args, switches (which we did manually in lesson 2), and aliases (which we didn't support at all).
To keep our CLI handling separate from our main app logic, we'll just call our main WordCount module with the parsed arguments and flags extracted by
The main module
Much of the main word count module will be familiar from Word Count ULTIMATE EDITION. The structure goes as follows:
If the input is valid, open the specified file
Read in the entire file as one binary (this could be changed to
Stream functions if we needed to support very large inputs)
Split the file into lines
Split the file into words using
Split the file into characters using
For each flag enabled, report the appropriate count
And then we're done!
Note: The word "native" was ill-chosen. Escript will let you run elixir programs directly from the command line, but they still run through the Erlang VM as opposed to being compiled for an x86 processor as with C or Rust.
escript implement a simple clone of Unix's
tail command. Implement its
--lines flag and its