这是我的镜头。我使用了 escript 所以它可以从命令行运行,但它可以很容易地放入一个模块中:
#!/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) ].
如果您不想使用列表推导,这是与最后一行代码类似的方法,使用 lists:foreach 和相同的序列:
% 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)
).