Perl unpack Function



This function unpacks the binary string STRING using the format specified in TEMPLATE. Basically reverses the operation of pack, returning the list of packed values according to the supplied format.

You can also prefix any format field with a %<number> to indicate that you want a 16-bit checksum of the value of STRING, instead of the value.


Following is the simple syntax for this function −


Return Value

This function returns the list of unpacked values.

Here is the table which gives values to be used in TEMPLATE.


Indicates "go back one byte"

S.No. Character & Description
1. a

ASCII character string padded with null characters

2. A

ASCII character string padded with spaces

3. b

String of bits, lowest first

4. B

String of bits, highest first

5. c

A signed character (range usually -128 to 127)

6. C

An unsigned character (usually 8 bits)

7. d

A double-precision floating-point number

8. f

A single-precision floating-point number

9. h

Hexadecimal string, lowest digit first

10. H

Hexadecimal string, highest digit first

11. i

A signed integer

12. I

An unsigned integer

13. l

A signed long integer

14. L

An unsigned long integer

15. n

A short integer in network order

16. N

A long integer in network order

17. p

A pointer to a string

18. s

A signed short integer

19. S

An unsigned short integer

20. u

Convert to uuencode format

21. v

A short integer in VAX (little-endian) order

22. V

A long integer in VAX order

23. x

A null byte

25. @

Fill with nulls (ASCII 0)


Following is the example code showing its basic usage −

#!/usr/bin/perl -w

$bits = pack("c", 65);
# prints A, which is ASCII 65.
print "bits are $bits\n";
$bits = pack( "x" );
# $bits is now a null chracter.
print "bits are $bits\n";
$bits = pack( "sai", 255, "T", 30 );
# creates a seven charcter string on most computers'
print "bits are $bits\n";

@array = unpack( "sai", "$bits" );

#Array now contains three elements: 255, A and 47.
print "Array $array[0]\n";
print "Array $array[1]\n";
print "Array $array[2]\n";

When above code is executed, it produces the following result −

bits are A
bits are 
bits are 􀳦T-
Array 255
Array T
Array 30