Hello World
From Erlang Community
Problem
You want to write the classic "Hello World!" program in Erlang.
Solution
This is very impractical in Erlang, but here you go:
$ erl -eval 'io:fwrite("Hello, world!\n").' -noshell -eval 'exit(0).'
Hello, world!
{"init terminating in do_boot",0}
Crash dump was written to: erl_crash.dump
init terminating in do_boot (0)
$
|
Discussion
To explain the above, I quote Erik Naggum's comments on comp.lang.lisp
The famous C program is famous for its ablity to produce an executable with a minimal amount of fuss. It really shows off the Unix environment, and not the language. However, an executable is only a funtcion that resides on disk in the Unix file sysem and which you call from the shell's read-execute interactive loop. Common Lisp systems offer their own interactive loop, called the read-eval-print loop and do not generally take part in the shell interactive loop the same way other languages do. Some find this a insurmountable obstacle to using Common Lisp, others love it. However, the code for the core program is simple: |
Erlang has a similar situation to that of Common Lisp (also: Smalltalk), although Erlang's is mitigated by its nodes, which are more easily thought of as little operating systems. But to make it clear: In Erlang you do not start a program from the unix shell, let it run its course, and then have it exit. Rather, you start one or many nodes and run programs within them. But if you'd like an example to show off the Erlang environment rather than the language:
in /foo/bar/baz/hello.erl |
-module(hello).
-export([hello/0]).
hello() -> io:fwrite("Hello, world!\n").
|
in a long-running Erlang node |
(mischief@mordor)199> cd("/foo/bar/baz").
/foo/bar/baz
(mischief@mordor)200> c(hello).
{ok,hello}
(mischief@mordor)201> hello:hello().
Hello, world!
ok
(mischief@mordor)202>
|
Alternatively, you could compile hello.erl separately:
$ erlc hello.erl |
in a long-running Erlang node |
(mischief@mordor)199> code:add_pathz("/foo/bar/baz").
(mischief@mordor)200> l(hello).
{module,hello}
(mischief@mordor)201> hello:hello().
Hello, world!
(mischief@mordor)202>
|
This is a quicker cycle that it might seem, here, and there's much more of interest in the environment than shown off, here. Just know that many people consider that the advantages of Erlang far outweigh not having the cute little unix executables celebrated by 'hello world' examples. This does constrain the sort of programs that you can sensibly write in Erlang, but so also are other languages constrained by not having Erlang nodes :-)

Digg It
Del.icio.us
Reddit
Facebook
Stumble Upon
Technorati

