pszals
pszals

Reputation: 23

Removing trailing ok from io:format in Erlang

I am building a simple tic tac toe program in Erlang. I pass the board as a string to io:format("123\n456\n789\n") and want to see:

123
456
789

But in the Erlang shell io:format("123\n456\n789\n") prints this:

123
456
789
ok

Is there a way to output to the console without the trailing ok?

Upvotes: 2

Views: 2332

Answers (4)

Ning
Ning

Reputation: 2880

Here is a workaround (It's just for fun:)):

> spawn(fun() -> timer:sleep(1000), io:format("123\n456\n789\n") end).
<0.77.0>
123 
456
789

Upvotes: -1

rvirding
rvirding

Reputation: 20916

The Erlang shell is a REPL, a Read/Eval/Print Loop. It reads a typed in expression, evaluates it, prints the result and loops to read the expression. The important thing to remember is that you enter an expression which always returns a value and the shell always prints the value. You cannot not return a value!

So when you enter io:format("123\n456\n789\n"). the shell evaluates the expression and prints the result. Evaluating the call to io:format results in the string being printed out and the call returns the value ok which the shell prints out. Hence you get

123
456
789
ok

Again the shell always prints the value returned by the expression. If you call io:format from within another function then its return value will generally not be returned to shell and the shell will not print it out.

Note that returning a value and printing something are two completely different things.

Upvotes: 1

Dmitry Belyaev
Dmitry Belyaev

Reputation: 2593

It's the shell, who prints that last ok atom. Try this:

erl -noshell -eval 'io:format("123\n456\n789\n"),init:stop()'

Upvotes: 4

Martin Kristiansen
Martin Kristiansen

Reputation: 10222

The ok is there to tell you that the call worked. The spec for the function io:format specifies this.

The real problem here is that you are seeing a mixture of the erlang terminal, and whatever is comming from stdout - stdout is printing the numbers, and the erlang terminal is giving back the ok.

if you were writing a script using escript, the ok stratement will not be printed to standart output - you should simply think of the console as an interactive interpreter.

As a side note the easiest way to output:

123
456
789

Would be

1> 123. 456. 789.
123
456
789

Upvotes: 6

Related Questions