[erlang-questions] strings vs binaries

zxq9 zxq9@REDACTED
Wed Aug 19 14:36:00 CEST 2015


On 2015年8月19日 水曜日 14:20:36 you wrote:
> On 08/19/2015 02:04 PM, zxq9 wrote:
> > For example:
> >
> > 1> io:format("~ts~n", [[["何か","何々"],"So why is this working?",<<"何か"/utf8>>]]).
> > 何か何々So why is this working?何か
> > ok
> 
> I'm not sure how ~ts works but since it's not expecting iolist() I'm 
> only half surprised.
> 
> Here's one though:
> 
> 1> file:write_file("/tmp/test.txt", [["何か","何々"],"So why is this 
> working?",<<"何か"/utf8>>]).
> {error,badarg}
> 2> file:write_file("/tmp/test.txt", ["So why is this working?",<<"何 
> か"/utf8>>]).
> ok
> 
> Here's another:
> 
> 3> {ok, S} = gen_tcp:connect("google.com", 80, []).
> {ok,#Port<0.548>}
> 4> gen_tcp:send(S, [["何か","何々"],"So why is this working?",<<"何 
> か"/utf8>>]).
> {error,einval}
> 5>
> =ERROR REPORT==== 19-Aug-2015::14:19:52 ===
> Bad value on output port 'tcp_inet'
> 5> gen_tcp:send(S, ["So why is this working?",<<"何か"/utf8>>]).
> ok

Ah, and that makes perfect sense. We have a function, zfile:write/2 where `zfile:write(File, Data)` expands in this case to:

file:write_file("foo.txt", unicode:characters_to_binary([[["何か","何々"],"So why is this working?",<<"何か"/utf8>>]], utf8)).

And this works just fine. There are similar wrappers for sockets in some places.

So the really magic functions aren't the output ones; we've wrapped them in the actually magical unicode:characters_to_binary/2, which appears to be capable of chewing through anything. This works well enough that I've not looked at the code in this module in at least a year and forgot this stuff was there!

Thanks for pointing that out, I could have tripped myself on this, not to mention putting out wrong poop on the ML and tripping up others. :-)

-Craig



More information about the erlang-questions mailing list