Eric Ivancich
unread,Nov 27, 2007, 11:51:31 AM11/27/07Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Midwest.erl
Hi Everyone,
I enjoyed last night's meeting, and I cleaned up my code quite a bit
as a result.
One issue we were dealing with was processing user terminal input.
This works, although if you were testing against two or more regexps,
it would be pretty clunky:
UserInput = io:get_line('(h)it or (s)tand? '),
Hit = case regexp:match(UserInput, "^[hH]") of
{match, _, _} -> yes;
nomatch -> no
end,
But what we really want is to test a string against a list of regexps
and returning some identifier when we find one that matches. I think
that's the solution Patrick envisioned and proposed. Well here's some
code:
% any_match/2 takes a string and a list, where each element of the
% list is a tuple containing a regular expression and match-value.
% Each regexp in the list is tested, in order, against the string, and
% when the first matches, it's match-value is returned. If no regexps
% match the string, then the atom 'nomatch' is returned.
any_match({match, _, _}, MatchValue, _String, _List) -> MatchValue;
any_match(nomatch, _MatchValue, _String, []) -> nomatch;
any_match(nomatch, _MatchValue, String, [{Regexp, MatchValue} | Rest])
->
any_match(regexp:match(String, Regexp), MatchValue, String, Rest).
any_match(String, MatchList) -> any_match(nomatch, ignored, String,
MatchList).
And that allows you to code something like this:
case any_match(UserInput, [{"^[Hh]", hit}, {"^[Ss]", stand}]) of
hit ->
% code for hit;
stand ->
% code for stand;
nomatch ->
io:format("Illegal input ~p.~n", [UserInput]),
% recurse so user can try again
end
Eric