pack
Converts a list of values into a binary string according to a template.
Takes a TEMPLATE string and a LIST of values and packs them into a
binary string. The template is a sequence of format characters, each
optionally followed by a repeat count or * (consume all remaining).
Common format characters:
a,A,Z– ASCII string (null-padded, space-padded, null-terminated)c,C– signed/unsigned char (8-bit)s,S– signed/unsigned short (16-bit native)l,L– signed/unsigned long (32-bit native)q,Q– signed/unsigned quad (64-bit native)n,N– unsigned short/long in network (big-endian) byte orderv,V– unsigned short/long in VAX (little-endian) byte orderf,d– single/double-precision float (native)H,h– hex string (high/low nybble first)w– BER compressed integerU– Unicode code pointx– null byte paddingX– back up one byte@– null-pad to absolute position(...)N– group with repeat count
Whitespace and #-comments in templates are ignored.
Synopsis
my $bin = pack("A10", "hello"); # space-padded string
my $bin = pack("NnA*", $long, $short, $str);
my $bin = pack("(A2)*", @pairs); # group repeat
Implementation Notes
perl5 reference:
pp_pack.c:3175PP_wrapped(pp_pack, 0, 1).C structure: dSP; dMARK; dORIGMARK; dTARGET; SV *cat = TARG; // pad[op_targ] pat_sv = *++MARK; // template is first arg after mark MARK++; // advance past template SvPVCLEAR(cat); // clear cat, preserve UTF-8 off SvUTF8_off(cat); packlist(cat, pat, patend, MARK, SP + 1); SP = ORIGMARK; PUSHs(cat);