字符串到二进制,常量和变量之间的差异

时间:2014-02-12 10:04:57

标签: string binary erlang type-conversion

有人可以解释一下为什么第二个陈述给出badarg

由于

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

2 个答案:

答案 0 :(得分:4)

<<"hello">>只是一种特殊的语法来创建一个二进制文件,其中包含字符串文字中的字节 - 它是<<$h, $e, $l, $l, $o>>的语法糖,以及它看起来像一个字符串(即列表)的事实(人物)只是巧合。

如果字符串在变量中,则不能直接将其插入二进制文件中;你需要明确地转换它:

ContentBinary = list_to_binary(Content),

答案 1 :(得分:1)

当您输入&lt;&lt;“hello”&gt;&gt;在控制台或程序中,它是一种快捷方式,表示将列表“hello”转换为二进制文件。然后控制台使用漂亮的打印格式来显示它。

当您将内容定义为“hello”列表时,语法快捷方式不再可用,并且erlang正在寻找有效类型(Type = integer | float | binary | bytes | bitstring | bits | utf8 | utf16 | utf32)并找到一个列表,这就是为什么你得到这个错误的参数exeption。

以下条目是正确的:

7> V1 = <<"hello">>.         
<<"hello">>
8> V2 = "hello".             
"hello"
9> V1 = list_to_binary(V2).  
<<"hello">>
相关问题