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

hi, here's a newbie question for you gurus...could someone explain to me what this block of code does? : i have this hash with numerical keys (see variable named 'data_id' and string values (see variable named 'data_val') associated with each key. this has is being converted into binary code to generate a file which is used by my customer's software...here's where the ascii values are being converted into binary; i'm just not clear on what's going on:
$bin_data .= pack("s", $data_id); if (length($data_val) < 255) { $bin_data .= pack("C", length($data_val)); } else { $bin_data .= pack("C", 0xff); $bin_data .= pack("s", length($data_val)); }
any help would be grately appreciated

Replies are listed 'Best First'.
Re: newbie question
by polettix (Vicar) on Jul 22, 2005 at 00:17 UTC
    What is your doubt exactly? pack explains quite well what the different transformation letters do to the input.

    About the logic, I observe that if the length of $data_val can be expressed using a single octet (i.e. is less than 256), you can encode it using a single char. Otherwise, you need to encode it as a string, so you keep char 0xff (AKA 255) to signal this different behaviour and then use "s" encoding. Of course, this special "escaping" semantic assigned to 255 does not allow you to use it for immediate encoding when length equals 255, so you restrict the test to lengths strictly less than 255.

    Flavio
    perl -ple'$_=reverse' <<<ti.xittelop@oivalf

    Don't fool yourself.
Re: Understanding pack syntax
by pg (Canon) on Jul 22, 2005 at 02:45 UTC

    Besides the pack() function, one of the purpose of this code is trying to reduce the size of the binary file base on the nature of the data.

    If the length of the value string is less than 255, you need 3 bytes (2 bytes for the id, and 1 byte for the length); else you need 5 bytes. You can pack the length with "s" regardless, in which case, you need 4 bytes every time. If the length is less than 255 for most of the time, your way obviously reduces the length of the binary file, otherwise it increases the length.