Reputation:
I have found this code in Ejabberd:
maybe_post_request([$< | _ ] = Data, Host, ClientIp)
I don't understand what [$< | _ ] = Data
part do with Data. Could somebody explain?
Upvotes: 3
Views: 76
Reputation: 20926
It's a way of having your cake and eating it at the same time. Data
refers to the whole thing while the [$<|_]
lets you match it and pull it apart. The putting then together with =
in a patterns allows you to do both. In a pattern like this it is generally called an alias. It means that both sides much match and in an argument in a function head (which is where you saw it) the order is irrelevant so the function head could have been written as
maybe_post_request([$< | _ ] = Data, Host, ClientIp)
or
maybe_post_request(Data = [$< | _ ], Host, ClientIp)
Of course in the function body or in the shell they are not equivalent.
I personally prefer the first alternative as that says matching, pulling apart to me.
Upvotes: 0
Reputation: 757
I don't understand what [$< | _ ] = Data part do with Data. Could somebody explain?
It binds the variable Data to the entire first argument to the function.
The left hand side pattern matches the first argument so that this function clause only matches when the first argument is a string (list) starting with the character <
. The variable Data is assigned the entire string fr use in the function body.
Upvotes: 1
Reputation: 20024
The construct
[$< | _] = Data
applies a pattern match to Data
, expecting it to be a list variable whose first element is the character <
and ignoring the rest the elements. Try it in the Erlang shell:
1> Data = "<foo>".
"<foo>"
2> [$<|_] = Data.
"<foo>"
But if Data
doesn't match, we get an exception:
3> f(Data), Data = "foo".
"foo"
4> [$<|_] = Data.
** exception error: no match of right hand side value "foo"
Upvotes: 6