Abhishek Abhishek - 3 months ago 17
Perl Question

extracting hex values from line in perl

I have a string like this, I need to extract only the hex values from line then copy the hex values in new file.

Input line in file:

ame (header(...)) 0x0D 0x0C 0x4A 0x00 0x01 0x00, 0x02 0x00, 0x0A 0x00,
0x04 0x00, 0x04 0x05 0x00 0x001f 0x001f 0x007f 0x00, 0x002b 0x007f 0x0000
0x00 0x0000 0xffffffaf 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0x00,
(non_t_crmax 0x0D 0x00, TDD 0x5D 0x2760 Invalid 0x0000 0x02 0x00,
(rat_type (rat_type (rat_type (rat_type (rat_type (rat_type (rat_type

Expected output:

0x0D, 0x0C, 0x4A, 0x00, 0x01, 0x00, 0x02, 0x00, 0x0A, 0x00, 0x04, 0x00,
0x04, 0x05,0x00, 0x001f, 0x001f, 0x007f, 0x00, 0x002b, 0x007f, 0x0000, 0x00
0x0000, 0xffffffaf,0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x0D,
0x00,0x5D 0x2760 0x0000 0x02 ,0x00,


All of the answers you have so far are correct, but they seem to make things far harder than necessary.


use strict;
use warnings;
use 5.010;

my @hex;
push @hex, /(0x[0-9a-f]+)/ig while <>;

$" = ',';
say "@hex";

This is written as a Unix filter (so much more flexible than hard-coding filenames) so it reads from STDIN and writes to STDOUT. Call it like this:

$ ./extract_hex < your_input_txt

It's actually possible to simplify even further and lose the intermediate @hex array.


use strict;
use warnings;
use 5.010;

say join ',', map { /(0x[0-9a-f]+)/ig } <>;

But that might be a little too terse for many people :-)