Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

What's the difference between chr() and pack('C',hex($1))?

by TGI (Parson)
on Oct 18, 2000 at 22:46 UTC ( [id://37388]=perlquestion: print w/replies, xml ) Need Help??

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.

  • Comment on What's the difference between chr() and pack('C',hex($1))?

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://37388]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2024-04-19 23:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found