2013-01-23 64 views
0

我似乎总是有使用2“结束”的问题的在代码例如相同的块:使用如果foreach循环内声明

Worker = fun (File) -> 
{ok, Device} = file:read_file([File]), 
Li = string:tokens(erlang:binary_to_list(Device), "\n"), 
Check = string:join(Li, "\r\n"), 
FindStr = string:str(Check, "yellow"), 
if 
    FindStr > 1 -> io:fwrite("found"); 
    true -> io:fwrite("not found") 
end, 
end, 

消息是“语法错误之前:‘结束’ “

回答

4

您需要删除逗号和结尾之间的逗号。

Worker = fun (File) -> 
{ok, Device} = file:read_file([File]), 
Li = string:tokens(erlang:binary_to_list(Device), "\n"), 
Check = string:join(Li, "\r\n"), 
FindStr = string:str(Check, "yellow"), 
if 
    FindStr > 1 -> io:fwrite("found"); 
    true -> io:fwrite("not found") 
end 
end, 
2

规则很简单 - 所有'语句'都要以逗号开头,除非它们恰好是最后一个。

您的if表达式是块中的最后一个(fun)传递给foreach。这意味着它不需要尾随,

所以

end 
end, 

是你所需要的。一个更简单的例子:

L = [1, 2, 3, 4], 
lists:foreach(
    fun(X) -> 
    Y = 1, 
    if 
     X > 1 -> io:format("then greater than 1!~n"); 
     true -> io:format("else...~n") 
    end 
    end, 
    L 
)