3

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!

3
  • 2
    What do you mean by a binary content? Commented Mar 15, 2018 at 19:42
  • 1
    If you mean that you read from a "binary" file (under :raw), then you'll need to unpack what you read before regex can work with it. (I don't know whether you consider that "easy" or not :) Commented Mar 15, 2018 at 19:52
  • The above comment stands corrected by ikegami answer. I'm leaving it for now since that may well be what you want to do, for convenience. Commented Mar 15, 2018 at 20:10

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That works only for single characters I think. I need it for whole strings that are in a scalar (e.g. s/$binval/$newval/)
No. Perl's regex engine will work with arbitrary strings. But that doesn't excuse the need to form a proper regex (s/\Q$binval\E/$newval/).
WOW! That is a real easy way!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.