2012-06-03 17 views
8

Estoy tratando de aprender erlang a través de interviewstreet. Acabo de aprender el idioma ahora, así que no sé casi nada. Me preguntaba cómo leer desde stdin y escribir en stdout.Erlang leer stdin escribir stdout

Quiero escribir un programa simple que escriba "¡Hola, mundo!" la cantidad de veces recibida en stdin.

Así que con la entrada de la entrada estándar:

6 

Comentario a la salida estándar:

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

Idealmente Leeré la línea de entrada estándar a la vez (a pesar de que es sólo un dígito en este caso) por lo Creo que usaré get_line. Eso es todo lo que sé por ahora.

gracias

, gracias

Respuesta

19

Aquí hay otra solución, tal vez más funcional.

#!/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). 
+1

+1 para la recursión de cola! – marcelog

1

aquí está mi oportunidad. He usado Escript por lo que se puede ejecutar desde la línea de comandos, pero se puede poner en un módulo fácilmente:

#!/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) ]. 

Si no desea utilizar una lista por comprensión, este es un enfoque similar al de la última línea de código, mediante el uso de listas: foreach y la misma secuencia:

% 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) 
    ). 
0
% Enter your code here. Read input from STDIN. Print output to STDOUT 
% Your class should be named solution 

-module(solution). 
-export([main/0, input/0, print_hello/1]). 

main() -> 
    print_hello(input()). 

print_hello(0) ->io:format(""); 
print_hello(N) -> 
    io:format("Hello World~n"), 
    print_hello(N-1). 
input()-> 
    {ok,[N]} = io:fread("","~d"), 
N. 
Cuestiones relacionadas