Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: parse hex-encoded string into array with regex

Tags:

regex

hex

perl

I'm quite new to Perl development, and I'd like to perform a following task:

My script receives hex-encoded string as command-line param. Then I must decode this string and write it to output file like a C++ array with initialization from data given. For example:

perl myscript.pl DEADBABEDEADBEEF and the output something like

const boost::array<char, 8> MyArray = { 0xDE, 0xAD, 0xBA, 0xBE, 0xDE, 0xAD, 0xBE, 0xEF };

What is the right way to do this with Perl regex? Of course, I could perform it in loop with substrings, but I believe that there should be more elegant way.

EDIT: the input string is of fixed length.

like image 947
Haspemulator Avatar asked Jul 16 '10 11:07

Haspemulator


1 Answers

Try this:

my $hex = "DEADBABEDEADBEEF";
my @a = map "0x$_", $hex =~ /(..)/g;

How it works:

First, $hex =~ /(..)/g in list context captures all 2-character substrings (the /g flag means global match). Then map() takes the list and transforms it to another one, using the "0x$_" expression for each element of the first list ($_ here is an alias for the element).

See also perldoc -f map.

like image 69
Eugene Yarmash Avatar answered Sep 28 '22 22:09

Eugene Yarmash