perl function unpack

w‮gi.ww‬iftidea.com

The unpack function in Perl is used to extract data from binary strings. It returns a list of values based on the format specified. Here is an example:

my $binary_string = "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C";
my ($first, $second, $third) = unpack("C3", $binary_string);

print "First byte: $first\n";   # Output: First byte: 1
print "Second byte: $second\n"; # Output: Second byte: 2
print "Third byte: $third\n";   # Output: Third byte: 3

In this example, we have a binary string with 12 bytes. We then use the unpack function to extract the first three bytes as unsigned characters (specified by the "C3" format string). The resulting values are then assigned to the $first, $second, and $third variables, which are then printed to the console.

Note that the format string can contain one or more conversion specifiers, which specify the type and number of values to extract. The most commonly used conversion specifiers are:

  • C: Unsigned character
  • c: Signed character
  • S: Unsigned short (2 bytes)
  • s: Signed short (2 bytes)
  • L: Unsigned long (4 bytes)
  • l: Signed long (4 bytes)
  • Q: Unsigned quad (8 bytes)
  • q: Signed quad (8 bytes)
  • A: Null-padded string
  • Z: Null-terminated string
  • x: Null byte or whitespace (ignored)
  • n: Network byte order (big-endian) short
  • N: Network byte order (big-endian) long

There are many other conversion specifiers available, as well as various modifiers that can be used to specify the endianness of the data, the byte order, and the alignment of the fields. You can find more information about the unpack function and the available format specifiers in the Perl documentation.