How can I parse space separated by six STDIN lines unpacked in Perl?

I have a Java program that splashes in hexadecimal format, separated by spaces, 16 bytes of raw packet received over the network. Since I do not want to change this code, I am passing the result to a Perl script, which theoretically can simply unpack from STDIN variables. The following is an example of entering a string in a Perl file:

  FF FF 09 7D 10 01 07 01 00 02 00 1D 00 00 00 00 00 06 06 00 07 00 
 | --garbage ----- | c-- | c-- | int --- | int --- | int --- | int --- | int --- | int --- | int- - |

(c for char / byte, int for 16-bit integer variable)

At first I wanted to use unpack to cleanly separate each line of input from the variables that I need. However, due to a space in the line, I'm not sure how to handle it (I can use "A" as a template, but then I could just use split!)

Is there an elegant way to use unpack() ? I am not a Perl master, but as I said earlier, use split , and then manually convert each hex to byte, and then use bit manipulation and masks to get what I want. Any other suggestions (if unpack doesn't save the day)?

+6
perl parsing unpack
source share
2 answers

Assuming these ints are in big-endian order, use

 #! /usr/bin/perl use warnings; use strict; # for demo only *ARGV = *DATA; while (<>) { my @fields = unpack "x5C2n7", pack "C*", map hex, split; print "[", join("][" => @fields), "]\n"; } __DATA__ FF FF 09 7D 10 01 07 01 00 02 00 1D 00 00 00 00 00 06 00 07 00 

It starts with packing in bytes ( C* ) according to their values. The unpack template has the following parts:

  • x5 skips five bytes
  • C2 decodes two unsigned char values
  • n7 decodes seven 16-bit unsigned integers

Output:

  $ ./dump-packets
 [1] [7] [256] [512] [7424] [0] [0] [1536] [1792] 
+8
source share

If you want to use decompression for decompressed data, you first need to pack it first. And you will need to remove the spaces before you do this.

In other words,

 $line =~ tr/ //d; # remove spaces $line = pack 'H*', $line; # convert hex to binary # Now you can use unpack. 
+3
source share

All Articles