Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting variable from case Warning

When developing with erlang, I sometimes use case statements like this

case Status of
    1 ->
        Variable = "Something";
    2 ->
        Variable = "Something else";
    3 ->
        Variable = {"Something very different", [1,2,3]}
end

to assign a value to a variable depending on some condition.

The problem is: if I use it after the case statement:

do_something(Variable),

I get a compilation warning:

Warning: variable 'Variable' exported from 'case'

What is the best practice in Erlang to assign values to variables depending on some conditions and avoid such warnings?

like image 632
Sergey Ovchinnik Avatar asked Sep 27 '16 09:09

Sergey Ovchinnik


2 Answers

The idiomatic way to do this in Erlang is to assign Variable the return value of case since case is an expression that returns the last expression's value from each branch:

Variable = case Status of
    1 -> "Something";
    2 -> "Something else";
    3 -> {"Something very different", [1,2,3]}
end
like image 75
Dogbert Avatar answered Nov 17 '22 11:11

Dogbert


This warning is not activated by default. You have to turn it on with the warn_export_vars option. For example, putting the code above into foo.erl:

$ erlc foo.erl

(no warning there)

$ erlc +warn_export_vars foo.erl
foo.erl:14: Warning: variable 'Variable' exported from 'case' (line 6)

I happen to think that there's nothing wrong per se with setting variables like this, so I don't turn that option on. (It's possible to write easy-to-read or hard-to-read code using either convention.)

like image 4
legoscia Avatar answered Nov 17 '22 11:11

legoscia