2013-01-23 65 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 
)