bittersweet
bittersweet

Reputation: 37

String to binary, difference between constant and variable conversion

Can somebody please explain me why the second statement gives a badarg?

Thanks

42> <<"hello">>.
<<"hello">>
43> Content = "hello".
"hello"
44> <<Content>>.
** exception error: bad argument

Upvotes: 1

Views: 79

Answers (2)

Pascal
Pascal

Reputation: 14042

When you type <<"hello">> in the console or in a program, it is a kind of shortcut that says take the list "hello" en convert it to binary. Then the console use the pretty print format to display it.

When you define Content as a the list "hello", the syntax shortcut is no more available, and erlang is looking for a valid type (Type= integer | float | binary | bytes | bitstring | bits | utf8 | utf16 | utf32 ) and find a list instead it is why you get this bad argument exeption.

the following entries are correct:

7> V1 = <<"hello">>.         
<<"hello">>
8> V2 = "hello".             
"hello"
9> V1 = list_to_binary(V2).  
<<"hello">>

Upvotes: 1

legoscia
legoscia

Reputation: 41568

<<"hello">> is just a special syntax to create a binary that contains the bytes in the string literal - it's syntactic sugar for <<$h, $e, $l, $l, $o>>, and the fact that it looks like a string (i.e., a list of characters) is just a coincidence.

If the string is in a variable, you can't insert it into the binary directly; you need to convert it explicitly:

ContentBinary = list_to_binary(Content),

Upvotes: 4

Related Questions