[erlang-questions] Basic Erlang case question

Serge Aleynikov saleyn@REDACTED
Thu Jul 10 13:05:03 CEST 2008


The compiler warns you about the potential risk of an unsafe variable. 
Aside from rewriting the case clause as Lev & Hynek suggested, you can 
use a guard expression with a distinct variable name:

case mnesia:transaction(F1) of
...
{atomic, [#system_info{data = MD5}]} when MD5 =:= MD5_Password ->
     {ok, password};
...
end

Note that the warning is not specific to the use of a record in pattern 
match - you'd get the same warning if you did:

case mnesia:transaction(F1) of
...
MD5_Password ->
     {ok, password};
...
end

Here's a tricky part - if you define some other use of MD5_Password 
between the first case statement and the second, the warning in your 
original code would go away.  It looks like when the variable exported 
from the case clause is used elsewhere as a rhs in pattern match then 
its safe to use it on lhs as well.

Serge


Alexander Lamb wrote:
> Hello List,
> 
> Here is a very simple code to search if a supplied password is correct  
> or not:
> 
> 				F1 = fun() -> mnesia:match_object(systems,  
> #system_info{full_attribute = {System_Name,admin_password}, _ = '_'},  
> read) end,
> 				case Password of
> 					[] -> MD5_Password = [];
> 					_Any -> MD5_Password = erlang:md5(Password)
> 				end,
> 				case mnesia:transaction(F1) of
> 					{atomic, []} 								  -> {error, unknown_system};
> 					{atomic, [#system_info{data = MD5_Password}]} -> {ok, password};
> 					{atomic, _}									  -> {error, bad_password};
> 					{aborted, Reason}							  -> {error, Reason}
> 				end
> 
> 
> 
> Basically, if supplied Password is empty, the MD5_Password must be  
> empty. If not, I encrypt the Password to compare it with stored version.
> 
> My problem is that it compiles with a warning:
> 
> ./cs_systems.erl:173: Warning: variable 'MD5_Password' exported from  
> 'case' (line 167)
> 
> Why? Obviously I am trying to match the password in the record I found  
> with the password I supply.
> 
> Thanks,
> 
> Alex
> 
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
> 




More information about the erlang-questions mailing list