Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

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

( #37388=categorized question: print w/ replies, xml ) Need Help??
Contributed by TGI on Oct 18, 2000 at 22:46 UTC
Q&A  > strings


Description:

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?

Answer: What's the difference between chr() and pack('C', hex($1))?
contributed by Fastolfe

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.

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others meditating upon the Monastery: (11)
    As of 2014-09-16 19:49 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      How do you remember the number of days in each month?











      Results (46 votes), past polls