chris01
chris01

Reputation: 12321

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!

Upvotes: 3

Views: 1965

Answers (1)

ikegami
ikegami

Reputation: 385657

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.

Upvotes: 5

Related Questions