[erlang-questions] variable exported from case in OTP 18

zxq9 zxq9@REDACTED
Tue Sep 29 13:58:41 CEST 2015

On 2015年9月29日 火曜日 20:42:19 zxq9 wrote:
> On 2015年9月29日 火曜日 11:06:48 Martin Koroudjiev wrote:
> > Hello,
> > 
> > I am confused why this code generates warning with the warn_export_vars
> > option:
> This has been discussed several times (here, for example: http://erlang.org/pipermail/erlang-questions/2014-March/078017.html), and because of the weirdness of case scope being one way (its a scope semantically and conceptually, but its not really) and list comprehensions being another (it really is a separate scope, but that's not how some other languages work) this has been made into a warning.


By the way -- something I should have mentioned is that this is almost never a problem in practice because the normal way to deal with lots of declarations within a `case` (usually because you have a large chain of case statements within a single function, so lots of bindings lay around in scope or collide) is to break most of this stuff out into separate functions.

For example, your original code is something I don't think anyone would write:

> test(Mode) ->
>     case Mode of
>         r -> {ok, FP} = file:open("warn.erl", [read]);
>         w -> {ok, FP} = file:open("warn.erl", [write])
>     end,
>     file:close(FP).

Would be more like:

test(Mode) ->
    {ok, FD} = file:open("warn.erl", [mode(Mode)]),
    ok = do_stuff(FD),

mode(r) -> read;
mode(w) -> write.

This bothered me initially because it is hard to imagine this being more natural any other way -- and its pretty weird to need 'r' or 'w' instead of 'read' or 'write' to begin with. But contrived examples are difficult to compare to real situations sometimes.


More information about the erlang-questions mailing list