문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top