Reputation: 4629
I am going through some extremely basic tutorials as I am just starting out with Erlang from a web background. I have the following file based off this forum post:
-module(calc).
-export([test/0]).
test() ->
X = io:get_line('X: ').
However, I do not get the expected results:
1> c(calc).
calc.erl:7: Warning: variable 'X' is unused
{ok,calc}
2> calc:test().
X: test
"test\n"
3> X.
* 1: variable 'X' is unbound
Shouldn't X = io:get_line('X: ').
bind X to the user input?
Upvotes: 0
Views: 360
Reputation: 5500
X
is only visible within the test
function and there are no global variables in Erlang. All values to be used outside a function needs to be returned to the function caller.
As it happens your test
function will return the value of X
as the function result (assignments are expressions => the bound value is the result and the last expression of a function is returned as the functions result).
So in the shell you could do X=calc:test().
to bind X
to the result.
A gotcha with variables, particularly when working with the shell, is that they are single-assignment. If you run X=calc:test().
twice in the shell, but type different data you will get an error the second time!
Use f(X).
in the shell to make X
unbound again.
Upvotes: 2