in reply to Re^2: how to unpack a C struct with length array preceding data array
in thread how to unpack a C struct with length array preceding data array
If anyone can explain what the quoted text means (specifically the integer arguments) or have a simpler example, I would appreciate that.Re:"For "unpack", an internal stack of integer arguments unpacked so far is used. You write "/"sequence-item and the repeat count is obtained by popping off the last element from the stack."
It means that the template character before the '/', must be one that unpacks an integer. That value is then used as the repeat count for the template character after the '/'.
So, if you use a template of 'C/A' the 'C' will unpack the first character of the string as a number and then its value will determine how many characters of the string are used by the 'A'.
Eg. Below, the C unpacks the first character "\x05", which is then used as the repeat count for the 'A', resulting the next 5 characters being unpacked.
say unpack "C/A", "\x05hellofred";; hello
Note. The reference to "the stack" refers to Perl's argument stack. As unpack processes each element of its template, the values extracted from the input string are pushed onto that stack, so that when the function returns, they are returned to the caller.
When the '/' is encountered, the last value pushed onto the stack is popped off again and used as the repeat count for the next template character. Hence, in the example above, the value '5' generated by the 'C' is not returned to the caller.
The <t1>/<t2> combination (where t1 can be any template char that results in a numeric value) is very useful for streaming communications protocols where you frequently have length-prefixed data items: <len1><data1><len2><data2>.
Unfortunately, there is no sensible way to use it for your struct format where you have <len1><len2><data1><data2>. (That is, I don't consider the absolute positioning solution above a "sensible" approach as it is not really extensible to more than 2 len/data pairs.
It will almost certainly always be quicker and cleaner to do that in two steps:
my( $len1, $len2 ) = unpack "SS", $packed; my( $data1, $data2 ) = unpack "x[SS] A$len1 A$len2", $packed;
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^4: how to unpack a C struct with length array preceding data array
by AnomalousMonk (Archbishop) on Jun 06, 2013 at 00:21 UTC | |
by BrowserUk (Patriarch) on Jun 06, 2013 at 02:01 UTC |