How to run easily your Erlang software (part I)
We saw in the last article, how to provide a very trivial Makefile in order to “install” in our system all the stuff necessary (e.g. configuration file)
Now we must find a way to run our code easily: in this post I will introduce you a possible solution to this, while next week I will teach you another possible implementation to solve the problem.
escript improves your “running” style😉
In this first post we take advantage of escript (the Erlang scripting support), a tool which gives support for running programs without having to compile them first. escript also provides an easy way to retrieve command line arguments.
Let’s see an easy example of code which takes as input an integer and gives its double as output:
$ less double #!/usr/local/bin/escript main([Input]) -> try Number = list_to_integer(Input), Double = double(N), io:format("The value of our input doubled is ~wn", [N]) catch _:_ -> usage() end; main(_) -> usage(). usage() -> io:format("Usage: double input (input is integer)n"), halt(1). double(N) -> N * 2.
Let’s see now how to run this code and let’s analyze the results:
$ double 5 The value of our input doubled is 10 $ double Usage: double input (input is integer) $ double five Usage: double input (input is integer)
You can notice that in the first line we invoke escript, obviously you may have installed your Erlang distribution in a different path, so I strongly recommend you to check your environment and change the first line according to your needs. Remember also that Erlang scripts will not work on Unix platforms without the needed rights. (Use chmod command for this).
An Erlang script file must always contain the function main/1 (we may think to it as to a C main function), this function is called with a list of strings representing the arguments given to the script, but these arguments are not treated in any way, so you have to take care of this in a second moment.
I told you before that the main function, behaves somehow as a C main function, in fact if the main/1 function in the script returns successfully, the exit status for the script will be 0, otherwise in case of exception generated during execution, it will return a non-zero exit code; you can achieve this using halt(ExitCode).
The script will be checked for syntactic and semantic correctness before being run. If there are warnings (such as unused variables), they will be printed and the script will still be run. If there are errors, they will be printed and the script will not be run and its exit status will be 127.
An interesting things to notice is the following: by default, the script is interpreted. If you wish, you may force it to be compiled by including the following line somewhere in the script file:
It is useful to remember that the execution of an interpreted code is slower than the one of a compiled code.
In the next post I will tell you another way for running you code! Keep reading and keep fit!