Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks
Could you please explain the below code, I didn't get much idea about pack function.
I got this code from internet,
$integer = pack("i", 171); $twoints = pack("i2", 103, 241);
The output for pack("i", 171) is 1/2 and if I change pack("i", 172), output is 1/4 and for pack("i", 173) some special character.... please explain this function.
Thanks

Replies are listed 'Best First'.
Re: Please explain the pack function
by Corion (Patriarch) on Apr 19, 2007 at 17:30 UTC

    The output was not 1/2, but ½, and it also wasn't 1/4, but ¼.

    Let's look at what the documentation for the pack function says:

    Takes a LIST of values and converts it into a string using the rules given by the TEMPLATE.

    So, the function takes a list of values (in our case, the number 171, or the number 172), and converts it into a string, according to our template. The template "i" says that pack is to take the values and pack them into integers in machine representation. Perl then returns the packed values as a string. If you look at the ASCII chart, you will find that at place 171, there is "½", at least for the character set you use. That's all there is to it.

    If you want to read some more information on pack, see the perlpacktut tutorial on pack.

      Corion, Thanks a lot for your help.
Re: Please explain the pack function
by BrowserUk (Patriarch) on Apr 19, 2007 at 18:06 UTC

    Maybe this will help?

    $integer = pack( 'i', 171 );; #The [pack] template 'i' converts a inte +ger print length( $integer );; # to a 4-byte string 4 # The first byte is ascii value 171 print ord( substr( $integer, $_, 1 ) ) for 0 .. 3;; 171 0 0 0 print chr( 171 );; ## Which displays as '½'. (On windows console,code +pages 437 & 850). ½ print chr( 172 );; ## Which displays as '¼'. (On windows console, code + pages 437 & 850). ¼

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      BrowserUk,Thanks a lot for your help.
Re: Please explain the pack function
by andye (Curate) on Apr 20, 2007 at 08:43 UTC