Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - replace regex match with arbitrary operation on regex

Tags:

regex

perl

I have the following line in my Perl script:

s/\b(\w+)\b/ $replaces{$1} ? $replaces{$1} : $1 /g;

I want to find all words in the string and if the word is in the array of known words replace it else keep it (ideally I want to do an arbitrary operation on match, not just ternary operator).

To do so I attempt to use ternary operator. Perl treats ? and : as literal symbol and just concats these with variables (if defined).

How do I cause Perl to treat ?: inside the replace as ternary operator?

P.S: I know that I can just perform operation on match in the next line of code but I want to keep it one liner for clarity.

like image 932
Muxecoid Avatar asked Jan 20 '23 21:01

Muxecoid


1 Answers

You need the 'e' (execute) qualifier:

s/\b(\w+)\b/ $replaces{$1} ? $replaces{$1} : $1 /ge;
like image 190
Jonathan Leffler Avatar answered Jan 31 '23 09:01

Jonathan Leffler