Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang read stdin write stdout

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

like image 877
GTDev Avatar asked Jun 03 '12 18:06

GTDev


2 Answers

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).
like image 188
tofcoder Avatar answered Nov 19 '22 04:11

tofcoder


Here's my shot at it. I've used escript so it can be run from the command line, but it can be put into a module easily:

#!/usr/bin/env escript

main(_Args) ->
    % Read a line from stdin, strip dos&unix newlines
    % This can also be done with io:get_line/2 using the atom 'standard_io' as the
    % first argument.
    Line = io:get_line("Enter num:"), 
    LineWithoutNL = string:strip(string:strip(Line, both, 13), both, 10),

    % Try to transform the string read into an unsigned int
    {ok, [Num], _} = io_lib:fread("~u", LineWithoutNL),

    % Using a list comprehension we can print the string for each one of the
    % elements generated in a sequence, that goes from 1 to Num.
    [ io:format("Hello world!~n") || _ <- lists:seq(1, Num) ].

If you dont want to use a list comprehension, this is a similar approach to the last line of code, by using lists:foreach and the same sequence:

    % Create a sequence, from 1 to Num, and call a fun to write to stdout
    % for each one of the items in the sequence.
    lists:foreach(
        fun(_Iteration) ->
            io:format("Hello world!~n")
        end,
        lists:seq(1,Num)
    ).
like image 37
marcelog Avatar answered Nov 19 '22 02:11

marcelog