Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: replace binary content

I need to replace a binary content with some other content (textual or binary) in Perl.

If the content is textual I can use s/// to replace content.

 my $txt = "tomturbo";
 $txt =~ s/t/T/g;      # TomTurbo

But that is not working if the content is binary.

Is there an easy way to handle that??

Thanks!

like image 402
chris01 Avatar asked Dec 14 '25 18:12

chris01


1 Answers

Perl's regex engine will work with arbitrary strings.

s/t/T/g

is no different than

s/\x{74}/\x{54}/g

meaning it will change the value of characters from 7416 to 5416. The regex engine doesn't care whether value 7416 means t or something else.

In binary data, character A16 doesn't indicate the end of a line, so you'll want to use the s flag, avoid the m flag, and avoid using $.

Furthermore, you'll find the i flag and the built-in character class (e.g. \d, \p{Letter}, etc) useless unless you are matching against strings of decoded text (strings of Unicode Code Points), but you may otherwise use any feature of the regex engine.

like image 116
ikegami Avatar answered Dec 16 '25 19:12

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!