Thursday, 12 December 2013

Running in the Shell

Ok so now to amend that hello script so that I can run it in the shell in a more mainstream fashion.  We need two additional lines at the start of the file, so:


The first line declares that this file constitutes a module called "hello".  The second line declares that this module exports a function called "main" which takes one parameter. The rest of the file is the same except I've added some line feeds to tidy up the output:

main([]) ->
    io:format("Hello World~n");
main([Arg]) ->
    io:format("Hello ~s~n", [Arg]);
main([Arg|More]) ->
    io:format("Hello ~s and~n", [Arg]),

Now on the command line we compile this so:

C:\Users\polly\Erlang>dir hello.*
12/12/2013  10:15               227 hello.erl
07/11/2013  13:32               186 hello.erl~
C:\Users\polly\Erlang>erlc hello.erl
C:\Users\polly\Erlang>dir hello.*
12/12/2013  10:21               688 hello.beam
12/12/2013  10:15               227 hello.erl
07/11/2013  13:32               186 hello.erl~

Ok the beam file is the compiled code.

Now to run the shell from the command line with the command erl:

Eshell V5.10.2  (abort with ^G)
1> l(hello).
2> hello:main(["Curly","Larry","Moe"]).
Hello Curly and
Hello Larry and
Hello Moe
3> q().

The numbered prompt 1> 2> etc are prompts in the shell.  The command l(hello) loads a module called "hello" from the appropriate beam file.  We then call the functions with the module - colon - function name format, as hello:main(...)

The command q(). returns the atom ok and then exits from the shell.