简体   繁体   中英

Perl - replace regex match with arbitrary operation on regex

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?

PS: 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.

你需要'e'(执行)限定符:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM