http://qs321.pair.com?node_id=37388

TGI has asked for the wisdom of the Perl Monks concerning the following question: (strings)

It seems that chr() and pack("C",hex($1)) do the same thing, namely convert a number into a character (from it's ASCII value). Is there an advantage to using one over the other? I've seen the pack approach used in several scripts, but never the chr form? Is something wrong with using chr?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: What's the difference between chr() and pack('C', hex($1))?
by Fastolfe (Vicar) on Oct 18, 2000 at 22:55 UTC
    There is a subtle difference that may bite you. chr works on characters while pack "C" works on bytes. With a standard ASCII character set, these are indistinguishable under most circumstances, but if you're using unicode (see perlunicode) data in later versions of Perl, chr and ord behave differently than their pack/unpack counterparts. pack/unpack will still work with individual bytes while chr/ord will actually deal with the full unicode character, which may be longer than 1 byte.