Erlang read stdin write stdout

GTDev picture GTDev · Jun 3, 2012 · Viewed 8.8k times · Source

I'm trying to learn erlang through interviewstreet. I just learning the language now so I know almost nothing. I was wondering how to read from stdin and write to stdout.

I want to write a simple program which writes "Hello World!" the number of times received in stdin.

So with stdin input:

6

Write to stdout:

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

Ideally I will read the stdin one line at a time (even though it's just one digit in this case) so I think I will be using get_line. That's all I know for now.

thanks

Thanks

Answer

tofcoder picture tofcoder · Jun 3, 2012

Here's another solution, maybe more functional.

#!/usr/bin/env escript

main(_) ->
    %% Directly reads the number of hellos as a decimal
    {ok, [X]} = io:fread("How many Hellos?> ", "~d"),
    %% Write X hellos
    hello(X).

%% Do nothing when there is no hello to write
hello(N) when N =< 0 -> ok;
%% Else, write a 'Hello World!', and then write (n-1) hellos
hello(N) ->
   io:fwrite("Hello World!~n"),
   hello(N - 1).