Fri Feb 25 19:18:51 CET 2005
Mats Cronqvist wrote:
> "...used in a binary construction, Value is an expression which should
> evaluate to an integer, float or string. If the expression is something
> else than a single literal or variable, it should be enclosed in
> this leads me to believe i should be able to do this;
> A = "123",
> alas, i get a badarg.
> can somone please point out my mistake?
The manual also states the following, a couple of lines below:
"Note that, for example, using a string literal as in <<"abc">> is
syntactic sugar for <<$a,$b,$c>>."
Unfortunately, that's all it is - syntactic sugar for a sequence of
integers (bytes, actually; Erlang uses iso8859-1). The previous
statement that the expression "should evaluate to ... or string" is
false; it may not evaluate to a string (list of integers) at runtime.
The suggestion by S. Bello that the string value is first explicitly
converted to a binary is probably the best that can be done in the
general case, but it depends on the context, i.e., what you want to
include with the string A in the binary. For example, there is no
point in doing:
A = list_to_binary(As),
B = list_to_binary(Bs),
Bin = <<A/binary, B/binary>>
(creating 2 temporary binaries) since you can simply do
Bin = list_to_binary([As,Bs])
if you're just concatenating bytes. (The deep list passed to
list_to_binary can also contain binaries.)
More information about the erlang-questions