Erlang basics · Lesson 27 (open contents)
Parse one real line
Trim a binary, split once, normalize its level, and return a tagged result.
Run this first
Run it once, change one input, and compare the new result.
%% Keep outside text at one boundary
Parse = fun(Line) ->
case binary:split(string:trim(Line), <<" ">>, [trim]) of
[] -> skip;
[<<"INFO">>, Message] -> {ok, {info, Message}};
[<<"WARN">>, Message] -> {ok, {warn, Message}};
_ -> {error, invalid_line}
end
end,
{Parse(<<"INFO ready">>), Parse(<<>>), Parse(<<"BROKEN">>)}.- The results show one accepted record,
skip, and{error,invalid_line}.
Read from the first line down
- Read
binary:split/3: Split the level from the remaining message. - Read
string:trim/1: Remove surrounding whitespace. - Read
{error, Reason}: Return malformed input as data.
Symbols are not secret signs
binary:split/3Split the level from the remaining message.
string:trim/1Remove surrounding whitespace.
{error, Reason}Return malformed input as data.
Match each name to its meaning
parser boundary
A parser turns outside text into a small internal data shape.
normalization
Normalization converts accepted spellings to one internal value.
complete result
Every input returns one documented result instead of falling through.
Why these forms are useful
Run the example first. Predict one result, then change one input and run it again.
A parser turns outside text into a small internal data shape.
Normalization converts accepted spellings to one internal value.
Close the answer and try
Accept an ERROR line.
[<<"ERROR">>, Message] -> {ok, {____, Message}};Target result: Use the atom error.
Stuck? Read one hint
The internal level is a known atom.
After you run it, see one answer
[<<"ERROR">>, Message] -> {ok, {error, Message}};Think about it: Why avoid creating atoms from arbitrary input?
Atoms are not garbage-collected in the usual way; unlimited outside values can exhaust the atom table.
Remember these three lines
- 1
Normalize at the boundary.
- 2
Return tagged failures.
- 3
Convert only known text to atoms.